Multi Step Form | CodingNepal

Многоэтапная форма

Здесь вы узнаете как сделать форму, которая заполняется в несколько этапов, при помощи CSS и JavaScript.

Мастер настройки — Многоэтапная форма

Как сделать многоэтапную форму

Шаг 1) Добавляем HTML:

  

Регистрация:

Как вас зовут:

Контактные данные:

Дата рождения:

Данные авторизации:

Шаг 2) Добавляем CSS:

Создаем стили для элементов формы.

 /* Стили формы */ #regForm < background-color: #ffffff; margin: 100px auto; padding: 40px; width: 70%; min-width: 300px; >/* Стили полей ввода */ input < padding: 10px; width: 100%; font-size: 17px; font-family: Raleway; border: 1px solid #aaaaaa; >/* Помечаем поля, у которых возникли ошибки валидации: */ input.invalid < background-color: #ffdddd; >/* Скрываем все этапы по умолчанию: */ .tab < display: none; >/* Создаем кружки, которые показывают этапы формы: */ .step < height: 15px; width: 15px; margin: 0 2px; background-color: #bbbbbb; border: none; border-radius: 50%; display: inline-block; opacity: 0.5; >/* Метим активный этап: */ .step.active < opacity: 1; >/* Метим завершенные и валидные этапы: */ .step.finish

Шаг 3) Добавляем JavaScript:

 var currentTab = 0; // Устанавливаем первую (0) вкладку как текущую showTab(currentTab); // Отображаем текущую вкладку function showTab(n) < // Эта функция отображает заданную вкладку формы . var x = document.getElementsByClassName("tab"); x[n].style.display = "block"; // . и фиксирует кнопки Назад/Дальше: if (n == 0) < document.getElementById("prevBtn").style.display = "none"; >else < document.getElementById("prevBtn").style.display = "inline"; >if (n == (x.length - 1)) < document.getElementById("nextBtn").innerHTML = "Отправить"; >else < document.getElementById("nextBtn").innerHTML = "Дальше"; >// . и запускает функцию, отображающую корректный индикатор этапа: fixStepIndicator(n) > function nextPrev(n) < // Это функция определяет какую вкладку отображать var x = document.getElementsByClassName("tab"); // Выйти из функции, если какое-нибудь поле текущей вкладки заполнено неверно: if (n == 1 && !validateForm()) return false; // Скрыть текущую вкладку: x[currentTab].style.display = "none"; // Увеличить или уменьшить номер текущей вкладки на 1: currentTab = currentTab + n; // если вы достигли конца формы. : if (currentTab >= x.length) < //. то данные формы отправляются на сервер: document.getElementById("regForm").submit(); return false; >// Иначе, отображаем нужную вкладку: showTab(currentTab); > function validateForm() < // Это функция проверяет заполнение полей формы var x, y, i, valid = true; x = document.getElementsByClassName("tab"); y = x[currentTab].getElementsByTagName("input"); // Цикл, который проверяет каждое поле ввода текущей вкладки: for (i = 0; i < y.length; i++) < // Если поле пустое. if (y[i].value == "") < // добавляем ему класс "invalid": y[i].className += " invalid"; // и устанавливаем текущий статус валидности в false: valid = false; >> // Если статус валидности true, помечаем этот шаг как завершенный и валидный: if (valid) < document.getElementsByClassName("step")[currentTab].className += " finish"; >return valid; // возвращаем статус валидности > function fixStepIndicator(n) < // Эта функция удаляет класс "active" у всех этапов. var i, x = document.getElementsByClassName("step"); for (i = 0; i < x.length; i++) < x[i].className = x[i].className.replace(" active", ""); >//. и добавляет класс "active" текущему этапу: x[n].className += " active"; > 

Источник

Register:

/* Make circles that indicate the steps of the form: */
.step height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbbbbb;
border: none;
border-radius: 50%;
display: inline-block;
opacity: 0.5;
>

/* Mark the active step: */
.step.active opacity: 1;
>

/* Mark the steps that are finished and valid: */
.step.finish background-color: #04AA6D;
>

Step 3) Add JavaScript:

Example

var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab

function showTab(n) // This function will display the specified tab of the form .
var x = document.getElementsByClassName(«tab»);
x[n].style.display = «block»;
// . and fix the Previous/Next buttons:
if (n == 0) document.getElementById(«prevBtn»).style.display = «none»;
> else document.getElementById(«prevBtn»).style.display = «inline»;
>
if (n == (x.length — 1)) document.getElementById(«nextBtn»).innerHTML = «Submit»;
> else document.getElementById(«nextBtn»).innerHTML = «Next»;
>
// . and run a function that displays the correct step indicator:
fixStepIndicator(n)
>

function nextPrev(n) // This function will figure out which tab to display
var x = document.getElementsByClassName(«tab»);
// Exit the function if any field in the current tab is invalid:
if (n == 1 && !validateForm()) return false;
// Hide the current tab:
x[currentTab].style.display = «none»;
// Increase or decrease the current tab by 1:
currentTab = currentTab + n;
// if you have reached the end of the form. :
if (currentTab >= x.length) //. the form gets submitted:
document.getElementById(«regForm»).submit();
return false;
>
// Otherwise, display the correct tab:
showTab(currentTab);
>

function validateForm() // This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName(«tab»);
y = x[currentTab].getElementsByTagName(«input»);
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) // If a field is empty.
if (y[i].value == «») // add an «invalid» class to the field:
y[i].className += » invalid»;
// and set the current valid status to false:
valid = false;
>
>
// If the valid status is true, mark the step as finished and valid:
if (valid) document.getElementsByClassName(«step»)[currentTab].className += » finish»;
>
return valid; // return the valid status
>

function fixStepIndicator(n) // This function removes the «active» class of all steps.
var i, x = document.getElementsByClassName(«step»);
for (i = 0; i < x.length; i++) x[i].className = x[i].className.replace(" active", "");
>
//. and adds the «active» class to the current step:
x[n].className += » active»;
>

Источник

Зарегистрироваться:

function showTab(n) // Эта функция отобразит указанную вкладку формы .
var x = document.getElementsByClassName(«tab»);
x[n].style.display = «block»;
// . и зафиксируйте кнопки Назад/Вперед:
if (n == 0) document.getElementById(«prevBtn»).style.display = «none»;
> else document.getElementById(«prevBtn»).style.display = «inline»;
>
if (n == (x.length — 1)) document.getElementById(«nextBtn»).innerHTML = «Отправить»;
> else document.getElementById(«nextBtn»).innerHTML = «Вперед»;
>
// . и запустите функцию, которая отображает правильный индикатор шага:
fixStepIndicator(n)
>

function nextPrev(n) // Эта функция определит, какую вкладку отображать
var x = document.getElementsByClassName(«tab»);
// Выйдите из функции, если какое-либо поле на вкладке текущий является недопустимым:
if (n == 1 && !validateForm()) return false;
// Скрыть текущую вкладку:
x[currentTab].style.display = «none»;
// Увеличение или уменьшение текущей вкладки на 1:
currentTab = currentTab + n;
// если вы дошли до конца формы. :
if (currentTab >= x.length) //. форма будет отправлена:
document.getElementById(«regForm»).submit();
return false;
>
// В противном случае отобразите правильную вкладку:
showTab(currentTab);
>

function validateForm() // Эта функция занимается проверкой полей формы
var x, y, i, valid = true;
x = document.getElementsByClassName(«tab»);
y = x[currentTab].getElementsByTagName(«input»);
// Цикл, который проверяет каждое поле ввода на текущей вкладке:
for (i = 0; i < y.length; i++) // Если поле пустое.
if (y[i].value == «») // добавьте в поле «invalid» класс:
y[i].className += » invalid»;
// и установите текущий допустимый статус в false:
valid = false;
>
>
// Если действительный статус равен true, отметьте шаг как завершенный и действительный:
if (valid) document.getElementsByClassName(«step»)[currentTab].className += » finish»;
>
return valid; // верните действительный статус
>

function fixStepIndicator(n) // Эта функция удаляет «активный» класс всех шагов.
var i, x = document.getElementsByClassName(«step»);
for (i = 0; i < x.length; i++) x[i].className = x[i].className.replace(" active", "");
>
//. и добавляет «активный» класс к текущему шагу:
x[n].className += » active»;
>

Источник

Multi Step Form with Step Progress Bar in HTML CSS & JavaScript

Multi Step Form with Step Progress Bar in HTML CSS & JavaScript

Hello readers, Today in this blog you’ll learn how to create a Multi Step Form with Step Progress Bar using HTML CSS & JavaScript. Earlier I have shared many blogs on how to create a Login Form using HTML & CSS. So now it’s time to create a Multi-Step Form in HTML.

A Multi-Step Form is a long-form that has broken into multiple pieces. This type of form asked you to enter your details step by step before submitting your form. Some Multi-Step Form has Step Progress Bar on the top of Form or on some website it’s placed on the bottom. Generally, This progress bar indicates or informs a user how many steps they have completed and how many steps are remaining.

As you have seen, this type of Multi-Step Forms in many websites. Some of them are created using Bootstrap. But today in this blog, I’ll share with you this program (Multi-Step Form with Step Progress) which is based on HTML CSS & JavaScript. I didn’t use any JavaScript library to create this form.

This form is long-form and it has broken into four steps. In each step, there are questions which user needs to enter. And I’ve also added a step progress bar on the top of the Form which indicates steps. There are two buttons (Next and Previous) on each step. When you click on the next button it’ll redirect you to the next step and when you click on the previous button it’ll redirect you to the previous step.

If you’re feeling difficulty understanding what I am saying. You can watch a full video tutorial on this program (Multi Step Form).

Video Tutorial of Multi Step Form in HTML & CSS

I hope you like this Multi-Step Form and understood the basic codes of this program. As you have seen in the video, I didn’t use any JavaScript library and CSS Framework to create this Multi-Step form. You can use this form on your websites and projects.

If you have basic knowledge of HTML CSS & JavaScript then you can also create this type of Multi-Step Form. Nowadays, this type of form is trending and used by many popular websites.

If you like this program (Multi-Step Form) and want to get source codes. You can easily get the source codes of this program. To get the source codes you just need to scroll down.

You might like this:

Multi-Step Form Using HTML CSS & JavaScript [Source Codes]

To create this program (Multi-Step Form). First, you need to create three Files (HTML, CSS & JavaScript). After creating these files just paste the following codes in your file. First, create an HTML file with the name of index.html and paste the given codes in your HTML file. Remember, you’ve to create a file with .html extension.

         
Signup Form

Name

1

Contact

2

Birth

3

Submit

4
Basic Info:
First Name
Last Name
Contact Info:
Email Address
Phone Number
Date of Birth:
Date
Gender
Login Details:
Username
Password

Second, create a CSS file with the name of style.css and paste the given codes in your CSS file. Remember, you’ve to create a file with .css extension.

@import url(‘https://fonts.googleapis.com/css?family=Poppins:400,500,600,700&display=swap’); * < margin: 0; padding: 0; outline: none; font-family: 'Poppins', sans-serif; >body < display: flex; align-items: center; justify-content: center; min-height: 100vh; overflow: hidden; background: url("bg.png"), -webkit-linear-gradient(bottom, #0250c5, #d43f8d); >::selection < color: #fff; background: #d43f8d; >.container < width: 330px; background: #fff; text-align: center; border-radius: 5px; padding: 50px 35px 10px 35px; >.container header < font-size: 35px; font-weight: 600; margin: 0 0 30px 0; >.container .form-outer < width: 100%; overflow: hidden; >.container .form-outer form < display: flex; width: 400%; >.form-outer form .page < width: 25%; transition: margin-left 0.3s ease-in-out; >.form-outer form .page .title < text-align: left; font-size: 25px; font-weight: 500; >.form-outer form .page .field < width: 330px; height: 45px; margin: 45px 0; display: flex; position: relative; >form .page .field .label < position: absolute; top: -30px; font-weight: 500; >form .page .field input < height: 100%; width: 100%; border: 1px solid lightgrey; border-radius: 5px; padding-left: 15px; font-size: 18px; >form .page .field select < width: 100%; padding-left: 10px; font-size: 17px; font-weight: 500; >form .page .field button < width: 100%; height: calc(100% + 5px); border: none; background: #d33f8d; margin-top: -20px; border-radius: 5px; color: #fff; cursor: pointer; font-size: 18px; font-weight: 500; letter-spacing: 1px; text-transform: uppercase; transition: 0.5s ease; >form .page .field button:hover < background: #000; >form .page .btns button < margin-top: -20px!important; >form .page .btns button.prev < margin-right: 3px; font-size: 17px; >form .page .btns button.next < margin-left: 3px; >.container .progress-bar < display: flex; margin: 40px 0; user-select: none; >.container .progress-bar .step < text-align: center; width: 100%; position: relative; >.container .progress-bar .step p < font-weight: 500; font-size: 18px; color: #000; margin-bottom: 8px; >.progress-bar .step .bullet < height: 25px; width: 25px; border: 2px solid #000; display: inline-block; border-radius: 50%; position: relative; transition: 0.2s; font-weight: 500; font-size: 17px; line-height: 25px; >.progress-bar .step .bullet.active < border-color: #d43f8d; background: #d43f8d; >.progress-bar .step .bullet span < position: absolute; left: 50%; transform: translateX(-50%); >.progress-bar .step .bullet.active span < display: none; >.progress-bar .step .bullet:before, .progress-bar .step .bullet:after < position: absolute; content: ''; bottom: 11px; right: -51px; height: 3px; width: 44px; background: #262626; >.progress-bar .step .bullet.active:after < background: #d43f8d; transform: scaleX(0); transform-origin: left; animation: animate 0.3s linear forwards; >@keyframes animate < 100%< transform: scaleX(1); >> .progress-bar .step:last-child .bullet:before, .progress-bar .step:last-child .bullet:after < display: none; >.progress-bar .step p.active < color: #d43f8d; transition: 0.2s linear; >.progress-bar .step .check < position: absolute; left: 50%; top: 70%; font-size: 15px; transform: translate(-50%, -50%); display: none; >.progress-bar .step .check.active

Last, create a JavaScript file with the name of script.js and paste the given codes in your JavaScript file. Remember, you’ve to create a file with .js extension.

 const slidePage = document.querySelector(".slide-page"); const nextBtnFirst = document.querySelector(".firstNext"); const prevBtnSec = document.querySelector(".prev-1"); const nextBtnSec = document.querySelector(".next-1"); const prevBtnThird = document.querySelector(".prev-2"); const nextBtnThird = document.querySelector(".next-2"); const prevBtnFourth = document.querySelector(".prev-3"); const submitBtn = document.querySelector(".submit"); const progressText = document.querySelectorAll(".step p"); const progressCheck = document.querySelectorAll(".step .check"); const bullet = document.querySelectorAll(".step .bullet"); let current = 1; nextBtnFirst.addEventListener("click", function(event)< event.preventDefault(); slidePage.style.marginLeft = "-25%"; bullet[current - 1].classList.add("active"); progressCheck[current - 1].classList.add("active"); progressText[current - 1].classList.add("active"); current += 1; >); nextBtnSec.addEventListener("click", function(event)< event.preventDefault(); slidePage.style.marginLeft = "-50%"; bullet[current - 1].classList.add("active"); progressCheck[current - 1].classList.add("active"); progressText[current - 1].classList.add("active"); current += 1; >); nextBtnThird.addEventListener("click", function(event)< event.preventDefault(); slidePage.style.marginLeft = "-75%"; bullet[current - 1].classList.add("active"); progressCheck[current - 1].classList.add("active"); progressText[current - 1].classList.add("active"); current += 1; >); submitBtn.addEventListener("click", function()< bullet[current - 1].classList.add("active"); progressCheck[current - 1].classList.add("active"); progressText[current - 1].classList.add("active"); current += 1; setTimeout(function()< alert("Your Form Successfully Signed up"); location.reload(); >,800); >); prevBtnSec.addEventListener("click", function(event)< event.preventDefault(); slidePage.style.marginLeft = "0%"; bullet[current - 2].classList.remove("active"); progressCheck[current - 2].classList.remove("active"); progressText[current - 2].classList.remove("active"); current -= 1; >); prevBtnThird.addEventListener("click", function(event)< event.preventDefault(); slidePage.style.marginLeft = "-25%"; bullet[current - 2].classList.remove("active"); progressCheck[current - 2].classList.remove("active"); progressText[current - 2].classList.remove("active"); current -= 1; >); prevBtnFourth.addEventListener("click", function(event)< event.preventDefault(); slidePage.style.marginLeft = "-50%"; bullet[current - 2].classList.remove("active"); progressCheck[current - 2].classList.remove("active"); progressText[current - 2].classList.remove("active"); current -= 1; >);

That’s all, now you’ve successfully created a Multi-Step Form with Step Progress Bar in HTML CSS & JavaScript. If your code doesn’t work or you’ve faced any error/problem then please download the source code files from the given download button. It’s free and a .zip file will be downloaded then you’ve to extract it.

Источник

Читайте также:  Updating database in java
Оцените статью