HTML-формы. Отправка данных формы Связь login form html

Here is an example of html login page code. In this example, we have displayed one text field, Password, Reset button and Login button. We have used Reset button that resets all fields to blank.We have used JavaScript validation in Login page. We have set username and password value.

Here is an example of html login page code. In this example, we have displayed one text field, Password, Reset button and Login button. We have used Reset button that resets all fields to blank.We have used JavaScript validation in Login page. We have set username and password value.

Here is an example of html login page code. In this example, we have displayed one text field, Password, Reset button and Login button. We have used Reset button that resets all fields to blank. We have used JavaScript validation in Login page. We have set username and password value. If a person enter a wrong username or password or both, an error message with "Error: Incorrect Username or Password" will be displayed. Till the person enters the correct username and password, it will not Login.

Once you enter the correct Username and Password, you will be redirected to another page.

Login page is used in most of the dynamic website to validate user based on their credentials. For making login page for websites HTML form and HTML elements are used. Text field is used to accept username and password text field is used to accept password from user.

The submit button is used for submitting data to server for validation. Its good to validate user input in the browser using JavaScript. In this tutorial we are creating a HTML Login page code and validating user input with JavaScript. In modern web application server-side validation is also very important it is done on server side with the program running on the server.

Here is video tutorial:

But in this tutorial you will learn to create a login page in HTML and validate user input with JavaScript. View demo of HTML Login page .

Here is the screen shot of the the login page we are making:

This login page displays Username, Password text fields and then buttons for reset and Login. Once user enters the data and clicks on the Login button, JavaScript is used to validate the form and error message is displayed if validation fails.

HTML Login page with JavaScript Validation

Login Page

HTML Login Page
Username:
Password:
function check(form) { if(form.userid.value == "Roseindia" && form.pwd.value == "Roseindia") { return true; } else { alert("Error Password or Username") return false; } }

The tag of HTML is the heart of creating user entry form in web application which takes the user input data and finally submit it to server side program for further processing. Data of all the input or hidden field is taken and submitted to the server through form tag. The "submit" button is used to initiate form data submit to the server. You can also use JavaScript code for submitting the form. For example if your form name is "loginForm" then following JavaScript code can be called for submitting the form programmatically.

HTML формы — сложные элементы интерфейса. Они включают в себя разные функциональные элементы: поля ввода и , списки , подсказки и т.д. Весь код формы заключается в элемент .

Большая часть информации веб-форм передаётся с помощью элемента . Для ввода одной строки текста применяется элемент , для нескольких строк - элемент . Элемент создает выпадающий список.

Элемент создаёт надписи к полям формы. Существует два способа группировки надписи и поля. Если поле находится внутри элемента , то атрибут for указывать не нужно.

Last Name Last Name Last Name

Поля формы можно разделять на логические блоки с помощью элемента . Каждому разделу можно присвоить название с помощью элемента .

Контактная информация Имя E-mail
Рис. 1. Группировка полей формы

Чтобы сделать форму более понятной для пользователей, в поля формы добавляют текст, содержащий пример вводимых данных. Такой текст называется подстановочным и создаётся с помощью атрибута placeholder .

Обязательные для заполнения поля также необходимо выделять. До появления HTML5 использовался символ звездочки * , установленный возле названия поля. В новой спецификации появился специальный атрибут required , который позволяет отметить обязательное поле на уровне разметки. Этот атрибут дает указание браузеру (при условии, что тот поддерживает HTML5), указание не отправлять данные после нажатия пользователем кнопки отправить, пока указанные поля не заполнены.

Для изменения внешний вид текстового поля при получении фокуса, используется псевдокласс focus . Например, можно сделать фон текущего поля более темным или добавить цветную рамку, чтобы оно выделялось среди остальных:

Input:focus { background: #eaeaea; }

Ещё один полезный html5-атрибут — атрибут autofocus . Он позволяет автоматически установить фокус на нужном начальном поле для элементов и (только в один элемент каждой формы).

Пример создания формы регистрации Регистрация Имя Пол мужской женский E-mail Страна Выберите страну проживания Россия Украина Беларусь Отправить

Примечание
action="form.php" — ссылка на файл обработчика формы. Создайте файл в кодировке UTF-8, закачайте его на сервер и замените action="form.php" на путь к файлу на вашем сервере.


Рис. 2. Внешний вид формы по умолчанию

Как видно из рисунка, каждый элемент формы имеет стили браузера по умолчанию. Очистим стили и оформим элементы формы.

Form-wrap { width: 550px; background: #ffd500; border-radius: 20px; } .form-wrap *{transition: .1s linear} .profile { width: 240px; float: left; text-align: center; padding: 30px; } form { background: white; float: left; width: calc(100% - 240px); padding: 30px; border-radius: 0 20px 20px 0; color: #7b7b7b; } .form-wrap:after, form div:after { content: ""; display: table; clear: both; } form div { margin-bottom: 15px; position: relative; } h1 { font-size: 24px; font-weight: 400; position: relative; margin-top: 50px; } h1:after { content: "\f138"; font-size: 40px; font-family: FontAwesome; position: absolute; top: 50px; left: 50%; transform: translateX(-50%); } /********************** стилизация элементов формы **********************/ label, span { display: block; font-size: 14px; margin-bottom: 8px; } input, input { border-width: 0; outline: none; margin: 0; width: 100%; padding: 10px 15px; background: #e6e6e6; } input:focus, input:focus { box-shadow: inset 0 0 0 2px rgba(0,0,0,.2); } .radio label { position: relative; padding-left: 50px; cursor: pointer; width: 50%; float: left; line-height: 40px; } .radio input { position: absolute; opacity: 0; } .radio-control { position: absolute; top: 0; left: 0; height: 40px; width: 40px; background: #e6e6e6; border-radius: 50%; text-align: center; } .male:before { content: "\f222"; font-family: FontAwesome; font-weight: bold; } .female:before { content: "\f221"; font-family: FontAwesome; font-weight: bold; } .radio label:hover input ~ .radio-control, .radiol input:focus ~ .radio-control { box-shadow: inset 0 0 0 2px rgba(0,0,0,.2); } .radio input:checked ~ .radio-control { color: red; } select { width: 100%; cursor: pointer; padding: 10px 15px; outline: 0; border: 0; background: #e6e6e6; color: #7b7b7b; -webkit-appearance: none; /*убираем галочку в webkit-браузерах*/ -moz-appearance: none; /*убираем галочку в Mozilla Firefox*/ } select::-ms-expand { display: none; /*убираем галочку в IE*/ } .select-arrow { position: absolute; top: 38px; right: 15px; width: 0; height: 0; pointer-events: none; /*активизируем показ списка при нажатии на стрелку*/ border-style: solid; border-width: 8px 5px 0 5px; border-color: #7b7b7b transparent transparent transparent; } button { padding: 10px 0; border-width: 0; display: block; width: 120px; margin: 25px auto 0; background: #60e6c5; color: white; font-size: 14px; outline: none; text-transform: uppercase; } /********************** добавляем форме адаптивность **********************/ @media (max-width: 600px) { .form-wrap {margin: 20px auto; max-width: 550px; width:100%;} .profile, form {float: none; width: 100%;} h1 {margin-top: auto; padding-bottom: 50px;} form {border-radius: 0 0 20px 20px;} }

Файл form.php

Примечание
В переменной $subject укажите текст, который будет отображаться как заголовок письма;
Ваше_имя — здесь вы можете указать имя, которое будет отображаться в поле «от кого письмо» ;
url_вашего_сайта замените на адрес сайта с формой регистрации;
ваш_email замените на ваш адрес электронной почты;
$headers .= "Bcc: ваш_email". "\r\n"; отправляет скрытую копию на ваш адрес электронной почты.

HTML теги, определяющие HTML формы на сайте

Создаем сайты и отдельные страницы в сети интернет для общения с посетителями.

HTML формы используются для регистрации посетителей на сайте, для интерактивных опросов и голосований, позволяют отправлять сообщения, совершать покупки и так далее. HTML Форма создается с одной целью: сбор и последующая передача информации на обработку программному сценарию или по электронной почте.

Пример HTML формы | Вход на сайт

Теги, атрибуты и значения

  • - определяют форму.
  • name="" - определяет имя формы.
  • method="" - определяет способ отправки данных из формы. Значения: "get" (по умолчанию) и "post" . Чаше используется метод "post" , так как позволяет передавать большие объемы данных.
  • action="" - определяет url по которому данные отправляются на обработку. В нашем случае - enter_data.php ..
  • - определяют такие элементы формы как кнопки, переключатели, текстовые поля для ввода данных.
  • type="text" - определяет текстовое поле для ввода данных.
  • type="password" - определяет поле для ввода пароля, при этом текст отображается в виде звездочек или кружочков.
  • type="checkbox" - определяет переключатель.
  • type="hidden" - определяет скрытый элемент формы - используется для передачи дополнительной информации на сервер.
  • size="25" - длина текстового поля в символах.
  • maxlength="30" - максимально допустимое количество вводимых символов.
  • value="" - определяет значение, которое будет отправлено на обработку если относится к радиобутонам или переключателям. Значение данного атрибута в составе текстового поля или кнопки будет показано как, например, Вася или Вход в примере выше.
Пример HTML формы | Комментарии на сайте
Пример HTML формы




Имя



Mail








Теги, атрибуты и значения

  • action="http://сайт/comments.php" - определяет url по которому будут отправлены данные из формы.
  • id="" - определяет имя, идентификатор элемента формы.
  • name="" - определяет имя элемента формы.
  • - определяют текстовое поле в составе формы.
  • cols="" - определяет количество колонок текстового поля формы.
  • rows="" - определяет количество рядов текстового поля формы.

Если между поместить текст, он будет показан внутри поля как пример, который легко удалить.

Пример HTML формы | Выпадающий список
HTML формы




Первая позиция
Вторая позиция
Третья позиция
Четвертая позиция

Теги, атрибуты и значения

  • - определяют список с позициями для выбора.
  • size="" - определяeт количество видимых позиций списка. Если значение равно 1 , мы имеем дело с выпадающим списком.
  • - определяют позиции (пункты) списка.
  • value="" - содержит значение, которое будет отправлено формой по указанному url на обработку.
  • selected="selected" - выделяет позицию списка в качестве примера.
Пример HTML формы | Список с полосой прокрутки

Увеличив значение атрибута size="" , мы получим список с полосой прокрутки:

Первая позиция Вторая позиция Третья позиция Четвертая позиция

HTML формы




Первая позиция
Вторая позиция
Третья позиция
Четвертая позиция

Для этого варианта применим флажок multiple="multiple" , который делает возможным выбор нескольких позиций. Его отсутствие разрешает выбрать только один пункт.

  • type="submit" - определяет кнопку.
  • type="reset" - определяет кнопку сброса.
  • value="" - определяет надпись на кнопке.
  • Смотрите дополнительно:

    Login forms are everywhere on the web. Are you using the social networks? You must go through login form of some sort. Do you have an email? Did you join any forums? Did you try to leave a comment on a WordPress site? To gain access to anything on the internet, the chances are you will have to go through some sort of login process. You will probably have to register first, sign up or leave some information behind. You will have to use some sort of login form to do anything on the internet.

    So what do Login Forms have to do with HTML and CSS? They are both the essential parts of the Login Forms.

    HTML (HyperText Markup Language) is a standard markup language used to create web pages. HTML elements are building blocks of all websites.

    CSS (Cascading Style Sheet) is a language used for describing the look and formatting of a document written in a markup language. Such as HTML!

    We use HTML to build a website and CSS to make it look nice. That is what most of the users encounter while browsing the web.

    We’ve made a list of 50 free login forms that you can use on your WordPress site, blog, forum or anywhere else. This is a hand-picked list by Colorlib to ensure the highest quality of the forms. Each and every form has been thoroughly tested to ensure no components are missing and source code is available with every download. Of course, you are free to use these forms for personal and commercial purposes, with no need for attribution.

    Explore 2.5 Million Digital Assets including 2019’s Best WordPress Templates

    2M+ items from the world’s largest marketplace for HTML5 Templates, Themes & Design Assets. Whether that’s what you need, or you’re just after a few Stock Photos – all of it can be found here at Envato Market.

    DOWNLOAD NOW

    WordPress Login Customizer

    The rest of the list and HTML/CSS powered login forms but here you can see the best login customizer plugin for WordPress. It comes with several defined templates that you can further tweak to match the design of your website. Thats to this plugin you can finally get rid of boring WordPress wp-admin page and create a truly unique experience for yourself and your users.

    Download Creative Login Form

    Simple yet creative login form created using HTML5 and CSS3. This form can be used as registration form as well. This is our favorite template on this list thanks to its flexibility and similarity that allows you to create

    WordPress version

    We did search the internet for cool login forms but it was very difficult to find good looking ones therefore we decided to have our take on them. We would like to present 20 login forms designed and developer by Colorlib team.

    Login Form 1 by Colorlib


    Simple, creative and vibrant login form with a gradient background. You can use this one for all sorts of intentions, like web, mobile or desktop applications. But do get creative with it if you like.

    WordPress version Login Form 2 by Colorlib


    Minimal and sophisticated login form by Colorlib with a gradient button with animation and a logo. Use it, alter it and have it as a nice addition to your already nifty web space.

    WordPress version Login Form 3 by Colorlib


    A gorgeous login page with a background image with shadow and a gradient form box with login button hover effect. The only limitation that you have is your imagination, so expand your view and use Login Form 3 to its full potential.

    WordPress version Login Form 4 by Colorlib


    Creativity knows no limits and nor does Login Form 4. Here it is, at your disposal, ready and set for you to download it and put it to some good use. Do not worry about the responsiveness either.

    WordPress version Login Form 5 by Colorlib


    Gorgeous, clean and modern form with an option to log in with Facebook or Google. All buttons have a nice hove effect that spices up the experience.

    WordPress version Login Form 6 by Colorlib


    If your page is already super neat and tidy, a login form should be no different. Here is one that will easily meet your expectations if minimalism is your cup of tea.

    WordPress version Login Form 7 by Colorlib


    A form with a three-way option of logging into the account. Either it is Facebook, Twitter or email login they prefer, this is the type of a tool that you need to feature on your page. And if they do not already have an account, you can also link it with your sign up page.

    WordPress version Login Form 8 by Colorlib


    Another contemporary, trendy and enticing login form with rounded everything. This one is especially applicable to mobile users due to its currently very popular rounded corners style.

    WordPress version Login Form 9 by Colorlib


    If you would like to avoid the white or single-color background, this is the login form page that you should consider. Not only does it support a full image background, but it also comes with a gradient overlay and an option to log in with Facebook or Google.

    WordPress version Login Form 10 by Colorlib


    A somewhat complete opposite compared to the previous one is Login Form 10. It almost could not be more minimalistic looking while still having this up-to-the-minute feel to it.

    WordPress version Login Form 11 by Colorlib


    With our collection of the best HTML5 and CSS3 login forms, you save yourself time and effort (money, too). Instead of building one from scratch, here is another killer ready-to-use template for you to employ.

    WordPress version Login Form 12 by Colorlib


    Image background with a blue shadow overlay, name, image and the must-have form, that’s what’s up with Login Form 12. There is also a cool hover effect on the login button and gives you a chance to link it with your registration form for all new users.

    WordPress version Login Form 13 by Colorlib


    A split screen sign up form, where one half is dedicated to an image and the other half to the form. It is a free tool which you can start using this very moment. Just download the layout and go full tilt with it.

    WordPress version Login Form 14 by Colorlib


    In this collection, we have a mixture of simplistic and those a tad more complex and advanced login forms. In short, there is something for everyone and Login Form 14 is more on the minimalistic side. But why even complicate with a login form, right? To each their own.

    WordPress version Login Form 15 by Colorlib


    While still keeping things to the bare minimum, one cool addition to the Login Form 15 is the image banner just above the form. With this little feature, you can make the experience slightly more engaging.

    WordPress version Login Form 16 by Colorlib


    This is a login form with a full-screen image on top of which is placed a form with username and password fields and a gradient button with hover effect. Simple and straightforward.

    WordPress version Login Form 17 by Colorlib


    To make it appear more personal, this framed login form template is the best fit for you. It has an image side and a form side but keeps things to the very minimum while still ensuring professionalism.

    WordPress version Login Form 18 by Colorlib


    If you like to differentiate yourself and keep things original, do consider using Login Form 18. While some enjoy login pages super basic, the others want to have some additional goodies rocking the layout. And if adding a picture is what you are after, this one is for you.

    WordPress version Login Form 19 by Colorlib


    Vibrant, energetic and attention-grabbing, that is what this next login form based on HTML5 and CSS3 is all about. It is also fully responsive and mobile-ready, as well as compatible with all major web browsers.

    WordPress version Login Form 20 by Colorlib


    Gradient background, black sign in button with hover effect, username and password fields along with custom text and “Forgot password?” section, yep, that’s all part of Login Form 20. Sounds overwhelming but in reality, far from it.

    WordPress version

    The form is hidden unless you click on “Login” option. Really great feature for modern websites that want to avoid having a separate page for the login form. You can display the form anywhere on your website with this powerful tool.

    Download

    A design for a Sign Up form using tabs and floating form labels.

    Download

    What was initially made to stop people from entering one person’s WordPress site, it became a really popular form due to its simplicity and neat design.

    Download Flat Login – Sign Up Form

    Once you click “Click me” button in top-right corner, you will get smooth animation that transforms this Login form to Sign up form.

    Download Login With Self-Contained SCSS Form

    This is a form with self-contained SCSS. An extension of CSS that adds power and elegance to the basic language. It allows to use variables, nested rules, mixins, inline imports, and more.

    Download

    This is actually an animated Login form, with top “Hey you, Login already” transforming into the form at the bottom. Smooth animation effects.

    Download

    This is an example on how to create a simple login form using HTML5 and CSS3. This form uses pseudo elements (:after and:before) to create the multi page effect. These elements are rotated using the CSS3 transform property. This form uses HTML5 to make validation and submission easy.

    Download

    Once you enter a wrong password in this form, a nice shake effect will warn you that you did not enter the correct password. A simple and effective solution that will point out the problem of incorrect passwords.

    Download

    A boxy login form with a little surprise. Try “admin” as a username, and “1234” as a password, for full experience.

    Download

    Neat little login form. Once you click on “LOGIN” on the left side, animation effect creates neat little login form on the right. Definitely unique approach!

    Download Material Design Form


    Fairly simple and easy on the eye login form that you can add to your blog or any other website and spice up the experience. No need to overcomplicate with a simple thing as the login form is. Even if you are just collecting subscribers, you can also play around with this layout and get things rocking.

    Download Bootstrap Snippet Form


    Obviously, this next free HTML5 login form is based on the well-liked Bootstrap Framework. This tells you that you can expect some nice flexibility that any modern website and element must practice. Email address, password and a check box to tick if a user would like the platform to remember his or her information. Easy and to the point.

    Download


    Regardless of your main web design, with things like login forms, you do not want to over complicate it. Instead, you would want to keep it simple and let it to the job, getting users to access their accounts seamlessly. You will achieve that goal with this login form with flat UI unquestionably.

    Download Trendy UI Kits Form


    From super simple login forms to those with slightly more action going on. This particular one is pretty similar compared to the last one just that you will notice a frame going all around the form. Get them to type in their names or usernames and passwords and they can enter your world of amazingness.

    Download Dashboard CSS3 HTML5 Form


    All the HTML5 and CSS3 login forms you find on this list are simple to use and effortless to attach to your web platform. This one even has a “Forgot your password?” right at the bottom for everyone who just cannot recall their passwords. The template is perfect for entering your dashboard, but you can apply it for other needs, too.

    Download Login With Recovery Form


    The title pretty much says it all; this is a neat, clean and minimal looking login form with recovery. What you also notice is that there is no traditional “box” that you are used to seeing login forms use. If you would like to make a difference, you now know which layout to choose.

    Download


    A free flat login form with a stunning and elegant dark layout coupled with a green call-to-action button. Sure, you can alter the tool to your likings, but you can also employ it exactly as is and have it live on your website in a snap. Play around with its features and have it all set up the way you like it.

    Download Transparent Login


    Even a login form can be of super creative and attention-grabbing nature. While many stick to the simple and basic look, there are others who like it special and exclusive. This transparent login form will surely do the trick for you. With an image background and a form over it, this layout can follow your branding to a T.

    Download


    No need to be really going too in-depth with this next login since it is pretty self-explanatory. It is compatible with the Google Chrome extension, as well as features buttons for those who are not signed up yet or lost their password. If this is the one you were looking for, then scrolling all the way this far was more than worth it.

    Download Elegant Flat Form


    A stylish flat form which you can append to your web space as a pop-up or ad as a widget on a page. Whatever the case, it will keep your professional approach intact. It is simple and easy on the eye and also has a CTA for everyone who missed signing up to your members’ area. Use it as is or improve it according to your taste.

    Download


    Definitely an approach to a free login form that you should not miss. It has a feel of a coupon just that it is not if that even makes any sense. Anyhow, in the text section, you can also link this form to the signup form for those interested in creating an account. Other than that, it surely will capture their attention.

    Download


    More and more website owners are implementing social logins and you can join the trend as well. This free login form with social integration is the right option to take the plunge. However, along with Twitter, Facebook and Google+ buttons, the layout also features the traditional way of signing up with an email.

    Download


    If your password is super complex, you sometimes just want to enter it in a “show” mode. Offer this same feature to all your users with the show and hide password login form. It has a stunning dark layout with green details perfect for those who dig this type of designs. Of course, feel free to make changes to it and fine-tune it according to your needs.

    Download Log ‘N Load Animated Form


    If you already practice animations and special effects on your page, keep the trend with the login form, too. Instead of creating your own one, you can simply use this striking Log ‘N Load animated form that will do the trick. Once you hover over the login button, the form reveals right in front of you. It even has a circular loading that enhances the experience.

    Download


    This flat, modern and easy to use login form works great on all devices, mobile, tablet and desktop. You can also play around with different tweaks and alter the default settings to your website’s style precisely. The tool also has cool hover effects that add a touch of sophistication to the overall experience.

    This is in continuation of the tutorial on making a membership based web site. Please see the previous page for more details.

    Download the code

    You can download the whole source code for the registration/login system from the link below:

    The ReadMe.txt file in the download contains detailed instructions.

    The login form

    Here is the HTML code for the login form.

    Login UserName*: Password*:

    Logging in

    We verify the username and the password we received and then look up those in the database. Here is the code:

    function Login() { if(empty($_POST["username"])) { $this->HandleError("UserName is empty!"); return false; } if(empty($_POST["password"])) { $this->HandleError("Password is empty!"); return false; } $username = trim($_POST["username"]); $password = trim($_POST["password"]); if(!$this->CheckLoginInDB($username,$password)) { return false; } session_start(); $_SESSION[$this->GetLoginSessionVar()] = $username; return true; }

    In order to identify a user as authorized, we are going to check the database for his combination of username/password, and if a correct combination was entered, we set a session variable.

    Here is the code to look up the username and password.

    function CheckLoginInDB($username,$password) { if(!$this->DBLogin()) { $this->HandleError("Database login failed!"); return false; } $username = $this->SanitizeForSQL($username); $pwdmd5 = md5($password); $qry = "Select name, email from $this->tablename ". " where username="$username" and password="$pwdmd5" ". " and confirmcode="y""; $result = mysql_query($qry,$this->connection); if(!$result || mysql_num_rows($result) HandleError("Error logging in. ". "The username or password does not match"); return false; } return true; }

    Please notice that we must compare the value for the password from the database with the MD5 encrypted value of the password entered by the user. If the query returns a result, we set an “authorized” session variable, and then redirect to the protected content. If there are no rows with the entered data, we just redirect the user to the login form again.

    Access controlled pages

    For those pages that can only be accessed by registered members, we need to put a check on the top of the page.
    Notice that we are setting an “authorized” session variable in the login code above. On top of pages we want to protect, we check for that session variable. If user is authorized, we show him the protected content, otherwise we direct him to the login form.

    Include this sample piece of code on top of your protected pages:

    See the file: access-controlled.php in the downloaded code for an example.

    Here is the CheckLogin() function code.

    function CheckLogin() { session_start(); $sessionvar = $this->GetLoginSessionVar(); if(empty($_SESSION[$sessionvar])) { return false; } return true; }

    These are the basics of creating a membership site. Now that you have the basic knowledge, you can experiment with it and add new features, such as a “Forgot password” page to allow the user to retrieve or change his password if he forgets it.

    Updates

    9th Jan 2012
    Reset Password/Change Password features are added.
    The code is now shared at GitHub .

    License


    The code is shared under LGPL license. You can freely use it on commercial or non-commercial websites.

    No related posts.

    Comments on this entry are closed.

    error: Content is protected !!