Проверка формы с использованием Javascript и PHP - PullRequest
0 голосов
/ 02 сентября 2018

Вот мой код, у меня проблемы с проверкой. Пожалуйста, скажите мне, что я делаю не так. У меня есть все перечисленное, что требуется для моего назначения, но я не могу понять, где я портю. Когда я заканчиваю регистрацию и перехожу к следующему шагу, именно здесь у меня возникают проблемы. После того, как я сделал выбор на странице интересов, я должен быть в состоянии зарегистрироваться и получить уведомление, поблагодарив меня за регистрацию, но ничего не происходит ... следующая страница или ошибка не отображаются. Я не знал, какую информацию предоставить, поэтому я предоставил все свои файлы HTML, javascript и php. Спасибо за любую помощь и руководство, которое вы можете предоставить, поскольку я студент и очень плохо знаком с Javascript.

Registration.html и Registration.js:

<!DOCTYPE html>
<html lang="en-US">

<head>
<title>Invitation Page</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/main.css" />
</head>
<script type="text/javascript">

function formValidation() {
// Make quick references to our fields.
var username = document.getElementById('userName');
var password = document.getElementById('password');
var passwordv = document.getElementById('passwordVerify');
var firstname = document.getElementById('firstName');
var lastname = document.getElementById('lastName');
var email = document.getElementById('email');
var phone = document.getElementById('phone');
var signup = document.getElementById('signUpNewsletter');

// To check empty form fields.
if (username.value.length == 0) {
document.getElementById('head').innerText = "* All fields are required 
*"; // This segment displays the validation rule for all fields
username.focus(); 
return false;
}
// Check each input in the order that it appears in the form.
if (textAlphanumeric(username, "* For your username please use alphabets 
and numbers only *")) {

if (lengthDefine(password, 8, 16 )) {
if (matchPass(password,passwordv,"* Passwords do not match! *" )) {
if (inputAlphabet(firstname, "* For your name please use alphabets only 
*")) {
if (inputAlphabet2(lastname, "* For your name please use alphabets only 
*")) {
if (emailValidation(email, "* Please enter a valid email address *")) {
if (textAlphanumeric(phone, "* Enter phone number in format (xxx)xxx-xxxx 
*")) {
}
}
}
}
}
}

return false;
}
// Function that checks whether input text is numeric or not.
function textNumeric(inputtext, alertMsg) {
var numericExpression = /^[0-9]+$/;
if (inputtext.value.match(numericExpression)) {
return true;
} else {
document.getElementById('p6').innerText = alertMsg; // This segment 
displays the validation rule for zip.
inputtext.focus();
return false;
}
}
// Function that checks whether input text is an alphabetic character or 
not.
function inputAlphabet(inputtext, alertMsg) {
var alphaExp = /^[a-zA-Z]+$/;
if (inputtext.value.match(alphaExp)) {
return true;
} else {
document.getElementById('p3').innerText = alertMsg; // This segment 
displays the validation rule for name.
//alert(alertMsg);
inputtext.focus();
return false;
}
}
// Function that checks whether input text is an alphabetic character or 
not.
function inputAlphabet2(inputtext, alertMsg) {
var alphaExp = /^[a-zA-Z]+$/;
if (inputtext.value.match(alphaExp)) {
return true;
} else {
document.getElementById('p4').innerText = alertMsg; // This segment 
displays the validation rule for name.
//alert(alertMsg);
inputtext.focus();
return false;
}
}
// Function that checks whether input text includes alphabetic and 
numeric characters.
function textAlphanumeric(inputtext, alertMsg) {
var alphaExp = /^[0-9a-zA-Z]+$/;
if (inputtext.value.match(alphaExp)) {
return true;
} else {
document.getElementById('p5').innerText = alertMsg; // This segment 
displays the validation rule for address.
inputtext.focus();
return false;
}
}
// Function that checks whether the input characters are restricted 
according to defined by user.
function lengthDefine(inputtext, min, max) {
var uInput = inputtext.value;
if (uInput.length >= min && uInput.length <= max) {
return true;
} else {
document.getElementById('p1').innerText = "* Please enter between " + min 
+ " and " + max + " characters *"; // This segment displays the 
validation rule for username
inputtext.focus();
return false;
}
}
// Function that checks whether the 2 passwords are correct.
function matchPass(pass1,pass2, alertMsg) {

if (pass1.value === pass2.value) {
return true;
} else {
document.getElementById('p2').innerText = alertMsg; // This segment 
displays the validation rule for username
pass2.focus();
return false;
}
}

// Function that checks whether an user entered valid email address or 
not and displays alert message on wrong email address format.
function emailValidation(inputtext, alertMsg) {
var emailExp = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
if (inputtext.value.match(emailExp)) {
return true;
} else {
document.getElementById('p5').innerText = alertMsg; // This segment 
displays the validation rule for email.
inputtext.focus();
return false;
}
}
// Function that checks whether an user entered valid phone number or not 
and displays alert message on wrong phone address format.
function phoneValidation(inputtext, alertMsg) {
var phoneExp = /^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1} 
[0-9]{4}$/;
if (inputtext.value.match(phoneExp)) {
document.getElementById("regform").submit();
return true;

} else {
document.getElementById('p6').innerText = alertMsg; // This segment 
displays the validation rule for email.
inputtext.focus();
return false;
}
}
}
</script>
<body>
<header>
<div class="top">
<a class="logo" href="index.html">CapellaVolunteers<span 
class="dotcom">.org</span></a>
</div>
<nav>
<ul class="topnav">
<li><a href="index.html">Home</a>
</li>
<li><a href="invitation.html">Invitation</a>
</li>
<li><a href="gallery.html">Gallery</a>
</li>
<li><a href="registration.html" class="active">Registration</a>
</li>
</ul>
</nav>
</header>
<section id="pageForm">
<form action="interests.html" id="regform" name="regform"  >

<p id="head"></p>
<label for="userName">Username:</label>
<input type="text" name="userName" id="userName" placeholder="Enter your 
Username" />

<p id="p1"></p>
<label for="Password">Password:
</label>
<input type="password" name="password" id="password" placeholder="Enter 
your Password" />

<p id="p2"></p>
<label for="passwordVerify">Verify your Password:
</label>
<input type="password" name="passwordVerify" id="passwordVerify" 
placeholder="Enter in your Password again" />

<p id="p3"></p>
<label for="firstName">First Name:
</label>
<input type="text" name="firstName" id="firstName" placeholder="Enter 
your First Name" />

<p id="p4"></p>
<label for="lastName">Last Name:
</label>
<input type="text" name="lastName" id="lastName" placeholder="Enter your 
Last Name" />

<p id="p5"></p>
<label for="email">Email:
</label>
<input type="text" name="email" id="email" placeholder="Enter your Email 
Address" />

<p id="p6"></p>
<label for="phoneNumber">Phone Number
</label>
<input type="text" name="phone" id="phone" placeholder="Enter your Phone 
Number" />

<p id="p7"></p>
<label for="signUpNewsletter">Sign up for newsletter:
</label>
<input type="radio" name="signUpNewsletter" id="signUpNewsletter" 
value="Yes" checked> Yes 
<input type="radio" name="signUpNewsletter" id="signUpNewsletter" 
value="No"> No
<input type="submit"  value="Next step">
</form>
</section>

<!--<footer>This events site is for IT-FP3215 tasks.
</footer>-->
</body>

</html>

Interest.html:

<!DOCTYPE html>
<html lang="en-US">

<head>
<title>Interests Page</title>
<link rel="stylesheet" type="text/css" href="css/main.css" />
</head>
<script type="text/javascript" src="js/interest.js"></script>
<body>
<header>
<div class="top">
<a class="logo" href="index.html">CapellaVolunteers<span 
class="dotcom">.org</span></a>
</div>
<nav>
<ul class="topnav">
<li><a href="index.html">Home</a>
</li>
<li><a href="invitation.html">Invitation</a>
</li>
<li><a href="gallery.html">Gallery</a>
</li>
<li><a href="registration.html" class="active">Registration</a>
</li>
</ul>
</nav>
</header>
<section id="pageForm">
<form action="confirm.html" id="addform">
<input type="hidden" name="userName" id="userName" />
<input type="hidden" name="password" id="password" />
<input type="hidden" name="passwordVerify" id="passwordVerify" />
<input type="hidden" name="firstName" id="firstName" />
<input type="hidden" name="lastName" id="lastName" />
<input type="hidden" name="email" id="email" />
<input type="hidden" name="phone" id="phone" />
<input type="hidden" name="signUpNewsletter" id="signup" />
<label for="checkbox">Interests:
</label><br/>

<input type="checkbox" class="check1" id="check1" name="interests" 
value="Swimming"> Swimming<br>
<input type="checkbox" name="interests" id="check2" class="check2"  
value="Travelling"> Travelling <br>
<input type="checkbox" name="interests" id="check3" class="check3" 
value="Reading"> Reading <br>

<label for="signUpNewsletter">Sign up for newsletter:
</label><br/>
<input type="radio" name="signUpNewsletter" id="signUpNewsletter" 
value="Yes" checked> Yes <br>
<input type="radio" name="signUpNewsletter" id="signUpNewsletter" 
value="No"> No<br>

<label for="comments">Comments:
</label><br/>
<textarea name="comments" id="comments" placeholder="Your Comments" 
rows="10" cols="60"> </textarea><br>

<label for="referred">Referred by:
</label><br>
<input type="text" name="referred" id="referred" placeholder="Enter who 
referred you" /><br>

<input type="button" value="Register" onclick="storeCookie()">
</form>
</section>

<footer>This events site is for IT-FP3215 tasks.
</footer>
</body>

</html>

Confirm.html:

<!DOCTYPE html>
<html lang="en-US">

<head>
<title>Interests Page</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/main.css" />
</head>
<script type="text/javascript" src="js/confirm.js"></script>

<body>
<header>
<div class="top">
<a class="logo" href="index.html">CapellaVolunteers<span 
class="dotcom">.org</span></a>
</div>
<nav>
<ul class="topnav">
<li><a href="index.html">Home</a>
</li>
<li><a href="invitation.html">Invitation</a>
</li>
<li><a href="gallery.html">Gallery</a>
</li>
<li><a href="registration.html" class="active">Registration</a>
</li>
</ul>

</nav>
</header>
<section id="pageFormContent">

Username: <p id="username">Placeholder</p>
Password: <p id="password">Placeholder</p>
First Name: <p id="firstName">Placeholder</p>
Last Name: <p id="lastName">Placeholder</p>
email: <p id="email">Placeholder</p>
Phone: <p id="phone">Placeholder</p>
Sign up News Letter: <p id="signup">Placeholder</p>
interest 1: <p id="username"></p>
Interest 2: <p id="username"></p>
Interest 3: <p id="username"></p>
Comments: <p id="phone">Placeholder</p>

<!--
Process content to display content on screen

-->
</section>

<footer>This events site is for IT-FP3215 tasks.
</footer>
</body>

</html>

PHP:

<?php

echo "You form is successfully submitted. Thank you for registering.";

?>

Validation.js:

//a function which splits the url into the different variabls
window.onload= function(){
var params = {};
var param_array = window.location.href.split('?')[1].split('&');//split 
the rul
for(var i in param_array){//save the parts in the arry
x = param_array[i].split('=');
params[x[0]] = x[1];
}
document.getElementById("userName").value = params.userName;//gets the 
values of the username

document.getElementById("password").value = params.password;//gets 
password value
document.getElementById("passwordVerify").value = params.passwordVerify;
document.getElementById("firstName").value = params.firstName;//first 
name
document.getElementById("lastName").value = params.lastName;
document.getElementById("email").value = params.email;
document.getElementById("phone").value = params.phone;
document.getElementById("signup").value = params.signUpNewsletter;

}
function storeCookie(){
var username=document.getElementById("userName").value; //saves the 
username in a variabe
document.cookie= "username=" + username; //saves the username variable in 
a cookie
alert(document.cookie);
var password=document.getElementById("password").value; //saves the 
password in a variable
document.cookie= "password=" + password; //saves the password varible in 
a cookie
var fname=document.getElementById("firstName").value;//saves the first 
name in a variable
document.cookie= "firstName=" + fname; //saves the firstname varible in a 
cookie
var lname=document.getElementById("lastName").value ; //saves the last 
name in a variable
document.cookie= "lastName=" + lname; //saves the lastnaem varible in a 
cookie
var email=document.getElementById("email").value; //saves the email in a 
variable
document.cookie= "email=" + email; //saves the email varible in a cookie
var phone=document.getElementById("phone").value ; //saves the phone in a 
variable
document.cookie= "phone=" + phone;//saves the phone varible in a cookie
var signup=document.getElementById("signup").value; ////saves the sign up 
value in a variable
document.cookie= "signUpNewsletter=" + signup;//saves the signup varible 
in a cookie
var comments=document.getElementById("comments").value; //saves the 
comments in a variable
document.cookie= "comments=" + comments; //saves the comments varible in 
a cookie
var referred=document.getElementById("referred").value;//saves the 
referred by value in a variable
document.cookie= "referred=" + referred; //saves the referred by varible 
in a cookie

if(document.querySelector('.check1').checked){ //check if the checkbox is 
checked if yes, it saves the value in  cookie
var interest1=document.getElementById("check1").value;
document.cookie= "interest1=" + interest1; 

}
if(document.querySelector('.check2').checked){  //check if the checkbox 
is checked if yes, it saves the value in  cookie
var interest2=document.getElementById("check2").value;
document.cookie= "interest2=" + interest2;

}    
if(document.querySelector('.check3').checked){  //check if the checkbox 
is checked if yes, it saves the value in  cookie
var interest3=document.getElementById("check3").value;
document.cookie= "interest3=" + interest3;

}
document.getElementById("addform").submit();//submits the form
}

1 Ответ

0 голосов
/ 03 сентября 2018

Найдены и решены проблемы:

registration.html:

  • Добавлены правильные теги meta в теги head.
  • Вы должны использовать в целом правильное имя страницы. Я решил использовать interests.html (не interest.html). Поэтому я изменил тег form на <form action="interests.html"...>.
  • Я добавил onsubmit="return formValidation();" в тег form, чтобы можно было проверить вашу форму.
  • Ошибка в строке 9: "script" element between "head" and "body". Я переместил <script type="text/javascript">...</script> между head тегами.
  • Дубликат идентификатора "signUpNewsletter" на <input type="radio" name="signUpNewsletter" id="signUpNewsletter". Вы НЕ ДОЛЖНЫ иметь дубликаты идентификаторов. Поэтому я изменил на «signUpNewsletter1» и «signUpNewsletter2».
  • Ошибки, возникающие на «ломаных» линиях. Я исправил все ошибки, поместив соответствующее значение и / или комментарий в ONE LINE.

interests.html:

  • Добавлены правильные теги meta в теги head.
  • Добавлен <script type="text/javascript" src="js/validation.js"></script> в теги head, чтобы вы могли получить доступ к функциям из «validation.js». В противном случае вы бы получили ошибку.
  • Я переименовал <script src="js/interest.js" ...></script> в <script src="js/interests.js" ...></script>.
  • Ошибка в строке 8: "script" element between "head" and "body". Я переместил <script type="text/javascript" src="js/interest.js"></script> между тегами head.
  • Дубликат идентификатора "signUpNewsletter" на <input type="radio" name="signUpNewsletter" id="signUpNewsletter". Вы НЕ ДОЛЖНЫ иметь дубликаты идентификаторов. Поэтому я изменил на «signUpNewsletter1» и «signUpNewsletter2».
  • Всегда закрывайте js-скрипт точкой с запятой (";"). Поэтому я добавил один в onclick="storeCookie();".
  • Ошибки, возникающие на «ломаных» линиях. Я исправил все ошибки, поместив соответствующее значение и / или комментарий в ONE LINE.

Confirm.html:

  • Добавлены правильные теги meta в теги head.
  • Ошибка в строке 9: "script" element between "head" and "body". Я переместил <script type="text/javascript" src="js/confirm.js"></script> между тегами head.
  • Дубликат идентификатора "username" в interest 1: <p id="username"></p>. Вы НЕ ДОЛЖНЫ иметь дубликаты идентификаторов. Поэтому я изменил на «интерес1», «интерес2» и «интерес3».
  • Дубликат ID "телефон" на Comments: <p id="phone">Placeholder</p>. Это должно быть Comments: <p id="comments">Placeholder</p>, поэтому я исправил это.

JS / validation.js:

  • Ошибки, возникающие на «ломаных» линиях. Я исправил все ошибки, поместив соответствующее значение и / или комментарий в ONE LINE.

Рекомендации:

  • Чтобы избежать множества ошибок, которые я обнаружил в вашем коде, вы должны начать использовать хорошую IDE, которая показывает, что ваш код подвержен ошибкам и которая может идеально отформатировать ваш код. Я лично использую Netbeans 8.2 - выберите загрузку библиотеки для PHP (4-й столбец на странице загрузки). Новейшая версия для PHP, например версия 9.0 появится в продаже очень скоро (возможно, через пару недель). Обратите внимание, что текущая выпущенная версия 9.0 предназначена только для Java-проектов! Так что подождите немного дальше, пока не выйдет новая библиотека 9.0 для PHP.
  • Чтобы добиться своей функциональности, вы должны использовать php-страницы вместо html-страниц. Чтобы можно было обрабатывать отправленные данные формы или URL-адрес по php-коду, а не по js-коду.
  • Каждый раз, когда вы запускаете страницу, откройте «Консоль» или «Инспектор» в соответствующем меню «Средства разработки» вашего браузера. Например, в браузере Firefox вы можете найти «Консоль» и «Инспектор» в меню «Инструменты> Веб-разработчик». С помощью этих инструментов вы можете увидеть возможные ошибки, возникающие на ваших страницах, или вы можете изучить структуру страницы. И многие другие интересные вещи могут быть достигнуты с помощью этих инструментов.

Примечания:

Я не менял текстовое содержание ваших страниц. Я принял правильные меры, чтобы привести ваш код в рабочее состояние без ошибок.

Страницы (с разрешенными кодами):

Все страницы содержат рабочий код. Просто используйте их вместо своих.

registration.html:

<!DOCTYPE html>
<html lang="en-US">
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
        <meta charset="UTF-8" />
        <!-- The above 3 meta tags must come first in the head -->

        <title>Invitation Page</title>

        <link rel="stylesheet" type="text/css" href="css/main.css" />

        <script type="text/javascript">
            function formValidation() {
                // Make quick references to our fields.
                var username = document.getElementById('userName');
                var password = document.getElementById('password');
                var passwordv = document.getElementById('passwordVerify');
                var firstname = document.getElementById('firstName');
                var lastname = document.getElementById('lastName');
                var email = document.getElementById('email');
                var phone = document.getElementById('phone');
                var signup = document.getElementById('signUpNewsletter');

                // To check empty form fields.
                if (username.value.length == 0) {
                    // This segment displays the validation rule for all fields
                    document.getElementById('head').innerText = "* All fields are required * ";
                    username.focus();
                    return false;
                }

                // Check each input in the order that it appears in the form.
                if (textAlphanumeric(username, "* For your username please use alphabets and numbers only * ")) {
                    if (lengthDefine(password, 8, 16)) {
                        if (matchPass(password, passwordv, "* Passwords do not match! *")) {
                            if (inputAlphabet(firstname, "* For your name please use alphabets only * ")) {
                                if (inputAlphabet2(lastname, "* For your name please use alphabets only * ")) {
                                    if (emailValidation(email, "* Please enter a valid email address *")) {
                                        if (textAlphanumeric(phone, "* Enter phone number in format (xxx)xxx-xxxx * ")) {
                                            return true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                return false;
            }

            // Function that checks whether input text is numeric or not.
            function textNumeric(inputtext, alertMsg) {
                var numericExpression = /^[0-9]+$/;

                if (inputtext.value.match(numericExpression)) {
                    return true;
                } else {
                    // This segment displays the validation rule for zip.
                    document.getElementById('p6').innerText = alertMsg;
                    inputtext.focus();
                    return false;
                }
            }

            // Function that checks whether input text is an alphabetic character or not.
            function inputAlphabet(inputtext, alertMsg) {
                var alphaExp = /^[a-zA-Z]+$/;

                if (inputtext.value.match(alphaExp)) {
                    return true;
                } else {
                    // This segment displays the validation rule for name.
                    document.getElementById('p3').innerText = alertMsg;
                    //alert(alertMsg);
                    inputtext.focus();
                    return false;
                }
            }

            // Function that checks whether input text is an alphabetic character or not.
            function inputAlphabet2(inputtext, alertMsg) {
                var alphaExp = /^[a-zA-Z]+$/;

                if (inputtext.value.match(alphaExp)) {
                    return true;
                } else {
                    // This segment displays the validation rule for name.
                    document.getElementById('p4').innerText = alertMsg;
                    //alert(alertMsg);
                    inputtext.focus();
                    return false;
                }
            }

            // Function that checks whether input text includes alphabetic and numeric characters.
            function textAlphanumeric(inputtext, alertMsg) {
                var alphaExp = /^[0-9a-zA-Z]+$/;

                if (inputtext.value.match(alphaExp)) {
                    return true;
                } else {
                    // This segment displays the validation rule for address.
                    document.getElementById('p5').innerText = alertMsg;
                    inputtext.focus();
                    return false;
                }
            }

            // Function that checks whether the input characters are restricted according to defined by user.
            function lengthDefine(inputtext, min, max) {
                var uInput = inputtext.value;

                if (uInput.length >= min && uInput.length <= max) {
                    return true;
                } else {
                    // This segment displays the validation rule for username.
                    document.getElementById('p1').innerText = "* Please enter between " + min
                            + " and " + max + " characters *";
                    inputtext.focus();
                    return false;
                }
            }

            // Function that checks whether the 2 passwords are correct.
            function matchPass(pass1, pass2, alertMsg) {
                if (pass1.value === pass2.value) {
                    return true;
                } else {
                    // This segment displays the validation rule for username.
                    document.getElementById('p2').innerText = alertMsg;
                    pass2.focus();
                    return false;
                }
            }

            // Function that checks whether an user entered valid email address or not and displays alert message on wrong email address format.
            function emailValidation(inputtext, alertMsg) {
                var emailExp = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;

                if (inputtext.value.match(emailExp)) {
                    return true;
                } else {
                    // This segment displays the validation rule for email.
                    document.getElementById('p5').innerText = alertMsg;
                    inputtext.focus();
                    return false;
                }
            }

            // Function that checks whether an user entered valid phone number or not and displays alert message on wrong phone address format.
            function phoneValidation(inputtext, alertMsg) {
                var phoneExp = /^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1} [0 - 9]{4}$ /;

                if (inputtext.value.match(phoneExp)) {
                    document.getElementById("regform").submit();
                    return true;
                } else {
                    // This segment displays the validation rule for email.
                    document.getElementById('p6').innerText = alertMsg;
                    inputtext.focus();
                    return false;
                }
            }
        </script>
    </head>
    <body>
        <header>
            <div class="top">
                <a class="logo" href="index.html">
                    CapellaVolunteers<span class="dotcom">.org</span>
                </a>
            </div>
            <nav>
                <ul class="topnav">
                    <li>
                        <a href="index.html">Home</a>
                    </li>
                    <li>
                        <a href="invitation.html">Invitation</a>
                    </li>
                    <li>
                        <a href="gallery.html">Gallery</a>
                    </li>
                    <li>
                        <a href="registration.html" class="active">Registration</a>
                    </li>
                </ul>
            </nav>
        </header>

        <section id="pageForm">
            <form action="interests.html" id="regform" name="regform" onsubmit="return formValidation();">
                <p id="head"></p>
                <label for="userName">Username:</label>
                <input type="text" name="userName" id="userName" placeholder="Enter your Username" />

                <p id="p1"></p>
                <label for="Password">Password:</label>
                <input type="password" name="password" id="password" placeholder="Enter your Password" />

                <p id="p2"></p>
                <label for="passwordVerify">Verify your Password:</label>
                <input type="password" name="passwordVerify" id="passwordVerify" placeholder="Enter in your Password again" />

                <p id="p3"></p>
                <label for="firstName">First Name:</label>
                <input type="text" name="firstName" id="firstName" placeholder="Enter your First Name" />

                <p id="p4"></p>
                <label for="lastName">Last Name:</label>
                <input type="text" name="lastName" id="lastName" placeholder="Enter your Last Name" />

                <p id="p5"></p>
                <label for="email">Email:</label>
                <input type="text" name="email" id="email" placeholder="Enter your Email Address" />

                <p id="p6"></p>
                <label for="phoneNumber">Phone Number</label>
                <input type="text" name="phone" id="phone" placeholder="Enter your Phone Number" />

                <p id="p7"></p>
                <label for="signUpNewsletter">Sign up for newsletter:</label>
                <input type="radio" name="signUpNewsletter" id="signUpNewsletter1" value="Yes" checked> Yes
                <input type="radio" name="signUpNewsletter" id="signUpNewsletter2" value="No"> No

                <input type="submit" value="Next step">
            </form>
        </section>

        <!--
        <footer>
            This events site is for IT-FP3215 tasks.
        </footer>
        -->
    </body>

</html>

interests.html:

<!DOCTYPE html>
<html lang="en-US">
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
        <meta charset="UTF-8" />
        <!-- The above 3 meta tags must come first in the head -->

        <title>Interests Page</title>

        <link rel="stylesheet" type="text/css" href="css/main.css" />

        <script type="text/javascript" src="js/validation.js"></script>
        <script type="text/javascript" src="js/interests.js"></script>
    </head>
    <body>
        <header>
            <div class="top">
                <a class="logo" href="index.html">
                    CapellaVolunteers<span class="dotcom">.org</span>
                </a>
            </div>
            <nav>
                <ul class="topnav">
                    <li>
                        <a href="index.html">Home</a>
                    </li>
                    <li>
                        <a href="invitation.html">Invitation</a>
                    </li>
                    <li>
                        <a href="gallery.html">Gallery</a>
                    </li>
                    <li>
                        <a href="registration.html" class="active">Registration</a>
                    </li>
                </ul>
            </nav>
        </header>

        <section id="pageForm">
            <form action="confirm.html" id="addform">
                <input type="hidden" name="userName" id="userName" />
                <input type="hidden" name="password" id="password" />
                <input type="hidden" name="passwordVerify" id="passwordVerify" />
                <input type="hidden" name="firstName" id="firstName" />
                <input type="hidden" name="lastName" id="lastName" />
                <input type="hidden" name="email" id="email" />
                <input type="hidden" name="phone" id="phone" />
                <input type="hidden" name="signUpNewsletter" id="signup" />

                <label for="checkbox">Interests:</label><br/>
                <input type="checkbox" name="interests" id="check1" class="check1" value="Swimming"> Swimming<br>
                <input type="checkbox" name="interests" id="check2" class="check2" value="Travelling"> Travelling <br>
                <input type="checkbox" name="interests" id="check3" class="check3" value="Reading"> Reading <br>

                <label for="signUpNewsletter">Sign up for newsletter:</label><br/>
                <input type="radio" name="signUpNewsletter" id="signUpNewsletter1" value="Yes" checked> Yes <br>
                <input type="radio" name="signUpNewsletter" id="signUpNewsletter2" value="No"> No<br>

                <label for="comments">Comments:</label><br/>
                <textarea name="comments" id="comments" placeholder="Your Comments" rows="10" cols="60"> </textarea><br>

                <label for="referred">Referred by:</label><br>
                <input type="text" name="referred" id="referred" placeholder="Enter who referred you" /><br>

                <input type="button" value="Register" onclick="storeCookie();">
            </form>
        </section>

        <footer>
            This events site is for IT-FP3215 tasks.
        </footer>
    </body>

</html>

Confirm.html:

Если вы хотите получить значения, отправленные из interests.html, то вам, возможно, следует импортировать js/validation.js в confirm.html. Вам решать.

<!DOCTYPE html>
<html lang="en-US">
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
        <meta charset="UTF-8" />
        <!-- The above 3 meta tags must come first in the head -->

        <title>Interests Page</title>

        <link rel="stylesheet" type="text/css" href="css/main.css" />

        <script type="text/javascript" src="js/confirm.js"></script>
    </head>
    <body>
        <header>
            <div class="top">
                <a class="logo" href="index.html">
                    CapellaVolunteers<span class="dotcom">.org</span>
                </a>
            </div>
            <nav>
                <ul class="topnav">
                    <li>
                        <a href="index.html">Home</a>
                    </li>
                    <li>
                        <a href="invitation.html">Invitation</a>
                    </li>
                    <li>
                        <a href="gallery.html">Gallery</a>
                    </li>
                    <li>
                        <a href="registration.html" class="active">Registration</a>
                    </li>
                </ul>
            </nav>
        </header>

        <section id="pageFormContent">
            Username: <p id="username">Placeholder</p>
            Password: <p id="password">Placeholder</p>
            First Name: <p id="firstName">Placeholder</p>
            Last Name: <p id="lastName">Placeholder</p>
            email: <p id="email">Placeholder</p>
            Phone: <p id="phone">Placeholder</p>
            Sign up News Letter: <p id="signup">Placeholder</p>
            interest 1: <p id="interest1"></p>
            Interest 2: <p id="interest2"></p>
            Interest 3: <p id="interest3"></p>
            Comments: <p id="comments">Placeholder</p>

            <!-- Process content to display content on screen -->
        </section>

        <footer>
            This events site is for IT-FP3215 tasks.
        </footer>
    </body>
</html>

JS / validation.js:

//a function which splits the url into the different variabls
window.onload = function () {
    var params = {};
    var param_array = window.location.href.split('?')[1].split('&'); //split the url

    for (var i in param_array) {//save the parts in the array
        x = param_array[i].split('=');
        params[x[0]] = x[1];
    }

    document.getElementById("userName").value = params.userName;//gets the values of the username
    document.getElementById("password").value = params.password;//gets password value
    document.getElementById("passwordVerify").value = params.passwordVerify;
    document.getElementById("firstName").value = params.firstName;//first name
    document.getElementById("lastName").value = params.lastName;
    document.getElementById("email").value = params.email;
    document.getElementById("phone").value = params.phone;
    document.getElementById("signup").value = params.signUpNewsletter;
};

function storeCookie() {
    var username = document.getElementById("userName").value; //saves the username in a variabe
    document.cookie = "username=" + username; //saves the username variable in a cookie

    var password = document.getElementById("password").value; //saves the password in a variable
    document.cookie = "password=" + password; //saves the password varible in a cookie

    var fname = document.getElementById("firstName").value;//saves the first name in a variable
    document.cookie = "firstName=" + fname; //saves the firstname varible in a cookie

    var lname = document.getElementById("lastName").value; //saves the last name in a variable
    document.cookie = "lastName=" + lname; //saves the lastnaem varible in a cookie

    var email = document.getElementById("email").value; //saves the email in a variable
    document.cookie = "email=" + email; //saves the email varible in a cookie

    var phone = document.getElementById("phone").value; //saves the phone in a variable
    document.cookie = "phone=" + phone;//saves the phone varible in a cookie

    var signup = document.getElementById("signup").value; ////saves the sign up value in a variable
    document.cookie = "signUpNewsletter=" + signup;//saves the signup varible in a cookie

    var comments = document.getElementById("comments").value; //saves the comments in a variable
    document.cookie = "comments=" + comments; //saves the comments varible in a cookie

    var referred = document.getElementById("referred").value;//saves the referred by value in a variable
    document.cookie = "referred=" + referred; //saves the referred by varible in a cookie

    if (document.querySelector('.check1').checked) { //check if the checkbox is checked if yes, it saves the value in  cookie
        var interest1 = document.getElementById("check1").value;
        document.cookie = "interest1=" + interest1;
    }

    if (document.querySelector('.check2').checked) {  //check if the checkbox is checked if yes, it saves the value in  cookie
        var interest2 = document.getElementById("check2").value;
        document.cookie = "interest2=" + interest2;
    }

    if (document.querySelector('.check3').checked) {  //check if the checkbox is checked if yes, it saves the value in  cookie
        var interest3 = document.getElementById("check3").value;
        document.cookie = "interest3=" + interest3;
    }

    document.getElementById("addform").submit();//submits the form
}
<Ч />

РЕДАКТИРОВАТЬ 1

Порядок вызова страниц:

Страницы сделаны так, чтобы называться:

Загрузить registration.html> Нажать «Следующий шаг» * Кнопка 1149 *> Загрузить interests.html> Нажать «Регистрация» * Кнопка 1152 *> Загрузить confirm.html.

Структура проекта:

Я могу заверить вас, что мои коды верны и проверены. Итак, сначала перепроверьте имена файлов, которые вы используете. Они должны быть такими, как представлено в структуре файловой системы ниже:

css
    main.css
js
    confirm.js
    interests.js
    validation.js
confirm.html
gallery.html
index.html
interests.html
invitation.html
registration.html

Активировать куки

Для правильного тестирования страниц вы ДОЛЖНЫ очищать куки (установленные кодом js/validation.js) перед каждым тестом. Итак, в Firefox перейдите в меню «История> Очистить недавнюю историю ...» и установите:

  • Диапазон времени для очистки : «Все».
  • Проверка Печенье и Кэш .

Затем нажмите кнопку «Очистить сейчас» .

Кроме того, чтобы cookie-файлы работали, необходимо установить в браузере значение ACCEPT COOKIES . Итак, если вы используете Firefox, следуйте этим инструкциям . У вас должны быть следующие настройки:

  • Принимать файлы cookie и данные сайта с веб-сайтов (рекомендуется) : проверено.
  • Хранить до :. Я бы выбрал «Firefox закрыт».
  • Принимать сторонние куки и данные сайта : "Всегда". Хотя «Никогда» лучше, для тестирования вашего проекта установите «Всегда».

И не забудьте проверить «Консоль» и «Инспектор».

Хотя другие вещи могут помешать работе страниц, я надеюсь, что приведенные выше меры приведут ваш проект в действие.

РЕДАКТИРОВАТЬ 2

Найдена проблема:

На странице registration.html функция formValidation() не возвращала true, даже если все поля были действительными. Я изменил сценарий JS соответственно сейчас. Обратите внимание, что ранее все остальные функции находились в функции formValidation(). Я вывел их наружу и изменил formValidation() так, чтобы он работал правильно. Снова проверьте registration.html.

Примечание:

В моих тестах не учитывалось, как работает функция проверки, но только в том случае, если страницы инициируют правильную отправку на другие страницы без нее. Затем, в конце концов, я также проверил, запущена ли функция. Когда я увидел, что он называется правильно, я остановил свои тесты. Так что это была моя вина. Я прошу прощения! Сейчас я провел полный тест, и он работает. Я надеюсь, что это будет работать и на ваших системах.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...