I have been trying to make a form that validates phone number and name, but whenever submit is entered it just inputs the same messages whether the fields are filled out or not. The message constantly appears and I can't figure it out
ETA: http://jsfiddle.net/6W3uU/
<body>
<form id="contact">
<fieldset id="contactInformation">
<legend>Contact Information</legend>
<p id="error"></p>
<label id="name">Name:</label>
<br>
<input type="text">
<br>
<br>
<label id="phoneNumber">Phone Number:</label>
<br>
<input type="text">
<br>
<br>
<label id="eMail">E-Mail Address:</label>
<br>
<input type="text">
<br>
<br>
<label id="address">Address:</label>
<br>
<input type="text">
<br>
<br>
<label id="city">City:</label>
<br>
<input type="text">
<br>
<br>
<label id="postalCode">Postal Code:</label>
<br>
<input type="text">
<br>
<br>
<label id="province">Province</label>
<br>
<select id="province">
<option id="choose">Choose Your Province</option>
<option id="alberta">Alberta</option>
<option id="britishColumbia">British Columbia</option>
<option id="manitoba">Manitoba</option>
<option id="newBrunswick">New Brunswick</option>
<option id="newfoundland">Newfoundland and Labrador</option>
<option id="northwestTerritories">Northwest Territories</option>
<option id="noviaScotia">Nova Scotia</option>
<option id="nunavut">Nunavut</option>
<option id="ontario">Ontario</option>
<option id="pei">Prince Edward Island</option>
<option id="quebec">Quebec</option>
<option id="saskatchewan">Saskatchewan</option>
<option id="yukon">Yukon Territory</option>
<br>
<br>
<br>
<label id="shippingCheckbox">Is your shipping information the same as your contact information?
<input type="radio" id="sameInfo">
<label>
Yes it is
</label>
<br>
<br>
<input type="radio" id="notSameInfo">
<label>
No it is not
</label>
<br>
<br>
<input type="submit" id="submit" name="submit" value="Submit">
</form>
<br>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>
And here is the script:
//script.js
var errorNotify = 'Sorry, we could not process your request because '
var errorField = [];
function formVal() {
var isValid = true;
for (var i = 0; i < errorField.length; i++ ) {
$(errorField[i]).removeClass('error');
}
errorField = [];
if(!nameCheck()) {
isValid = false;
}
if(!phoneCheck()) {
isValid = false;
}
if (isValid === false) {
$('#error').html(errorNotify).hide().slideDown('slow');
for (var i = 0; i < errorField.length; i++) {
$(errorField[i]).addClass('error');
}
errorNotify = 'Sorry, we could not process your request because ';
}
function nameCheck(){
if ($('#name').val() === '') {
errorNotify += ' you did not enter your name.';
errorField.push($('#name'));
return false;
} else {
return true;
}
}
function phoneCheck(){
var phoneCheck = $('#phoneNumber').val();
if (phoneCheck === '') {
errorNotify += ' you did not enter your phone number.';
errorField.push($('#phoneNumber'));
return false;
} else if (phoneCheck.length !== 10) {
errorNotify += 'please enter a 10 digit phone number';
errorField.push($('#phoneNumber'));
}
else if (isNaN(parseInt(phoneCheck))) {
errorNotify += 'you have entered a letter, please enter a number';
errorField.push($('#phoneNumber'));
}
else {
return true;
}
}
return isValid;
}
$(function () {
$('#contact').submit(function() {
return formVal();
});
});
You have your ids on the label tags, not the input fields, change
<label id="name">Name:</label>
<br>
<input type="text">
to
<label for="name">Name:</label>
<br>
<input id="name" type="text">
etc
Related
I added the onclickevent to the button, but it still doesn't output my form correctly.
By default, buttons inside a form have a type of submit, which means that the button will automatically submit the form when clicked.
To fix, the quickest way would be to add a type="button" property to your button:
function clearErrors() {
document.getElementById("firstnameError").innerHTML = "";
document.getElementById("lastnameError").innerHTML = "";
document.getElementById("usernameError").innerHTML = "";
}
function processForm() {
clearErrors();
var output = "";
if (document.getElementById("firstname").value == "") {
document.getElementById("firstnameError").innerHTML = "First name required";
}
if (document.getElementById("lastname").value == "") {
document.getElementById("lastnameError").innerHTML = "Last name required";
}
output += "The form would submit the following information:"
output += "\nFirst name: " + document.getElementById("firstname").value;
output += "\nLast name: " + document.getElementById("lastname").value;
if (document.getElementById("male").checked == true) {
output += "\nSex: Male";
} else {
output += "\nSex: Female";
}
if (document.getElementById("car").checked == true) {
output += "\nI have a car";
}
var education = document.getElementById("education");
output += "\nEducation: " + education.options[education.selectedIndex].text;
document.getElementById("output").value = output;
}
<div id="header">
<h1>HTML Forms</h1>
</div>
<div id="content">
<form id="detailsForm">
<p>
First name:<input type="text" name="firstname" id="firstname" />* <span id="firstnameError"></span><br /> Last name:<input type="text" name="lastname" id="lastname" />* <span id="lastnameError"></span><br /> Username:
<input type="text" name="username" id="username" />* <span id="usernameError"></span><br /> Male <input type="radio" name="sex" value="male" id="male" /> Female<input type="radio" name="sex" value="female" id="female" checked /> <br /> I have a
car:<input type="checkbox" name="vehicle" value="Car" id="car" /><br /> Select a Level of Education:<br />
<select name="education" id="education">
<option value="Secondary School">Secondary School</option>
<option value="University">University</option>
</select> <br />
<button type="button" onclick="processForm()">Click me</button>
</p>
<p>
<textarea name="output" id="output" rows="10" cols="100"></textarea>
</p>
</form>
</div>
I recreated your code as a snippet. It's working fine.
(Modified your code to have the eventListener() added in JS and not in HTML.)
function clearErrors() {
document.getElementById("firstnameError").innerHTML = "";
document.getElementById("lastnameError").innerHTML = "";
document.getElementById("usernameError").innerHTML = "";
}
function processForm() {
clearErrors();
var output = "";
if (document.getElementById("firstname").value == "") {
document.getElementById("firstnameError").innerHTML = "First name required";
}
if (document.getElementById("lastname").value == "") {
document.getElementById("lastnameError").innerHTML = "Last name required";
}
output += "The form would submit the following information:"
output += "\nFirst name: " + document.getElementById("firstname").value;
output += "\nLast name: " + document.getElementById("lastname").value;
if (document.getElementById("male").checked == true) {
output += "\nSex: Male";
} else {
output += "\nSex: Female";
}
if (document.getElementById("car").checked == true) {
output += "\nI have a car";
}
var education = document.getElementById("education");
output += "\nEducation: " + education.options[education.selectedIndex].text;
document.getElementById("output").value = output;
}
var btnSubmit = document.getElementById('btnSubmit')
btnSubmit.addEventListener('click', function(e) {
e.preventDefault()
processForm()
})
<div id="header">
<h1>HTML Forms</h1>
</div>
<div id="content">
<form id="detailsForm">
<p>
First name:<input type="text" name="firstname" id="firstname" />* <span id="firstnameError"></span><br /> Last name:<input type="text" name="lastname" id="lastname" />* <span id="lastnameError"></span><br /> Username:
<input type="text" name="username" id="username" />* <span id="usernameError"></span><br /> Male <input type="radio" name="sex" value="male" id="male" /> Female<input type="radio" name="sex" value="female" id="female" checked /> <br /> I have a
car:
<input type="checkbox" name="vehicle" value="Car" id="car" /><br /> Select a Level of Education:<br />
<select name="education" id="education">
<option value="Secondary School">Secondary School</option>
<option value="University">University</option>
</select> <br />
<button id="btnSubmit">Click me</button>
</p>
<p>
<textarea name="output" id="output" rows="10" cols="100"></textarea>
</p>
</form>
</div>
So, what I want to accomplish here is to prevent people from entering the rest of the form until they focus on the first section by hiding the last section until the value of a certain field is greater than nothing.
Here is my HTML:
<div class="fieldcontainer">
<label>E-mail:</label>
<input type="email" name="email" maxlength="100" id="email" required>
</div>
<br><br>
<div id="projectinformation" style="display:none">
<h3>Project Information</h3>
<div class="fieldcontainer">
<label>Project Name:</label>
<input type="text" name="project_name" maxlength="70" required>
</div>
<br><br>
<div class="fieldcontainer">
<label>Project Number:</label>
<input type="text" name="project_number" required>
</div>
<br><br>
<div class="fieldcontainer">
<label>Business Unit:</label>
<select name="business_unit" required>
<option>--Select--</option>
</select>
</div>
<br><br>
<div class="fieldcontainer">
<label>Project Address:</label>
<input type="text" name="address" required>
</div>
<br><br>
<div class="fieldcontainer">
<label>Number of users on site:</label>
<select id="numberofstaff">
<option class="staffselection" value="">--Select--</option>
<option class="staffselection" value="smalljobsite">1-3 staff</option>
<option class="staffselection" value="mediumjobsite">4-7 staff</option>
<option class="staffselection" value="largejobsite">8+ staff</option>
</select>
</div>
</div>
Here is my JS:
while (document.getElementById('email').value > ""){
document.getElementById('projectinformation').style.display = 'initial';
}
You'd probably want an event handler for that, and check the inputs value length, then show the rest of the form
document.getElementById('email').addEventListener('input', function() {
if ( this.value.length > 0 ) {
document.getElementById('projectinformation').style.display = 'block';
}
}, false);
or in jQuery
$('#email').on('input', function() {
if (this.value.length > 0) $('#projectinformation').show();
});
Here is jQuery solution:
$("#email").keyup(function() {
if($(this).val().length)
$('#projectinformation').show();
else
$('#projectinformation').hide();
});
If you want to validate if it is a valid email and then show the form, you can do this: (https://stackoverflow.com/a/2855946/1845408):
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
$("#email").keyup(function() {
if(isValidEmailAddress($(this).val())) {
$('#projectinformation').show();
else
$('#projectinformation').hide();
});
I have form with validations using Javascript. All of the drop downs are not validating. Any help?
<form id="itsp-form" method="post" action="http://www.url.com/save_itsp.php">
<label class="custom">Company name</label>
<input id="company_name" type="text" name="company_name" />
<label class="custom">Company URL</label>
<input id="company_url" type="text" name="company_url" />
<label class="custom">Company address</label>
<input id="company_address" type="text" name="company_address" />
<label class="custom">Type of business</label>
<select id="type_of_business[]" name="type_of_business[]" multiple="multiple">
<option value="" selected="selected"></option>
<option value="enterprise">Business sector/Enterprise</option>
<option value="residential">Residential</option>
<option value="wholesale">Wholesale VoIP Carrier</option>
<option value="other">Other</option>
</select>
<label class="custom">Areas served</label>
<select id="areas_served[]" name="areas_served[]" multiple="multiple">
<option value="" selected="selected"></option>
<option value="USA">USA</option>
<option value="Canada">Canada</option>
<option value="other">Other</option>
</select>
<br />
<label class="custom">Sales contact</label><br />
<h4>Name</h4>
<input id="sales_name" type="text" name="sales_name" />
<h4>Phone</h4>
<input type="text" name="sales_phone" />
<h4>Email</h4>
<input type="text" name="sales_email" />
<br />
<label class="custom">Testing contact</label><br />
<h4>Name</h4>
<input id="testing_name" type="text" name="testing_name" />
<h4>Phone</h4>
<input type="text" name="testing_phone" />
<h4>Email</h4>
<input type="text" name="testing_email" />
<br />
<label class="custom">Switch Platform</label>
<select id="switch_platform[]" name="switch_platform[]" multiple="multiple">
<option value="" selected="selected"></option>
<option value="asterisk">Asterisk</option>
<option value="broadsoft">Broadsoft</option>
<option value="metaswitch">Metaswitch</option>
<option value="sipx">SipX/eZuce</option>
<option value="other">Other</option>
</select>
<label class="custom">Interested In Testing</label>
<select id="interested_in_testing[]" name="interested_in_testing[]" multiple="multiple">
<option value="" selected="selected"></option>
<option value="atas">ATAs</option>
<option value="ip_phones">IP Phones</option>
<option value="gateways">Gateways</option>
<option value="ip_pbx">IP PBX</option>
</select>
<input type="submit" id="submit" value="Submit" />
<script>
$('#submit').click(function() {
$('.error').hide();
var hasError = false;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (($("#company_name").val() == '') || ($("#type_of_business[]").val() == '')) {
$("#errors").after('<span class="error">Please enter your Company name.</span>');
hasError = true;
}
if (($("#company_url").val() == '') || ($("#company_address").val() == '')) {
$("#errors").after('<span class="error">Please enter your Company information.</span>');
hasError = true;
}
if ($("#areas_served[]").val() == '') {
$("#errors").after('<span class="error">Please enter your Areas served.</span>');
hasError = true;
}
if ($("#type_of_business[]").val() == '') {
$("#errors").after('<span class="error">Please enter your Type of business.</span>');
hasError = true;
}
if ($("#sales_name").val() == '') {
$("#errors").after('<span class="error">Please enter your Sales contact information.</span>');
hasError = true;
}
if ($("#testing_name").val() == '') {
$("#errors").after('<span class="error">Please enter your Tester contact information</span>');
hasError = true;
}
if ($("#switch_platform[]").val() == '') {
$("#errors").after('<span class="error">Please enter your Switch platform</span>');
hasError = true;
}
if ($("#interested_in_testing[]").val() == '') {
$("#errors").after('<span class="error">Please enter your Testing interests.</span>');
hasError = true;
}
if(hasError == true) { return false; }
});
Your problem is that your ids are using square brackets [] which in jquery is an attribute-equals-selector. See http://api.jquery.com/attribute-equals-selector/
I would recommend not using square brackets in your id strings. Although permissible by html5, I would stick to using standard word and digit characters [a-zA-Z_0-9] to avoid issues with javascript tools and libraries
If you still want to use square brackets you must escape them. See jQuery selector for inputs with square brackets in the name attribute.
If you are using <input type='submit'>, the form will be submitted no matter what.
Try using <input type='button'> it may work then.
I can't figure out why but my script is not working properly as it was working fine before. Now, it is not working anymore and I can't figure out why as I don't remember making any changes to the script tag.
<body>
<form id="contact">
<fieldset id="contactInformation">
<legend>Contact Information</legend>
<p id="error"></p>
<label for="name">Name:</label>
<br>
<input id="name" type="text">
<br>
<br>
<label for="phoneNumber">Phone Number:</label>
<br>
<input id="phoneNumber" type="text">
<br>
<br>
<label id="eMail">E-Mail Address:</label>
<br>
<input type="text">
<br>
<br>
<label id="address">Address:</label>
<br>
<input type="text">
<br>
<br>
<label id="city">City:</label>
<br>
<input type="text">
<br>
<br>
<label id="postalCode">Postal Code:</label>
<br>
<input type="text">
<br>
<br>
<label id="province">Province</label>
<br>
<select id="province">
<option>Choose Your Province</option>
<option>Alberta</option>
<option>British Columbia</option>
<option>Manitoba</option>
<option>New Brunswick</option>
<option>Newfoundland and Labrador</option>
<option>Northwest Territories</option>
<option>Nova Scotia</option>
<option>Nunavut</option>
<option>Ontario</option>
<option>Prince Edward Island</option>
<option>Quebec</option>
<option>Saskatchewan</option>
<option>Yukon Territory</option>
</select>
<br>
<br>
<div id="shipping">
<label id="shippingCheckbox">Is your shipping information the same as your contact information?</label>
<br>
<br>
<input type="checkbox" id="sameInfo">
<label>Yes it is</label>
<br>
<br>
</div>
<fieldset id="shippinginformation">
<legend>Shipping Information</legend>
<label for="phoneNumber">Phone Number:</label>
<br>
<input id="phoneNumber" type="text">
<br>
<br>
<label id="address">Address:</label>
<br>
<input type="text">
<br>
<br>
<label id="postalCode">Postal Code:</label>
<br>
<input type="text">
<br>
<br>
</fieldset>
<br>
<input type="submit" id="submit" name="submit" value="Submit">
</form>
<br>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>
//script.js
var errorNotify = 'Sorry, we could not process your request because '
var errorField = [];
function formVal() {
var isValid = true;
for (var i = 0; i < errorField.length; i++ ) {
$(errorField[i]).removeClass('error');
}
errorField = [];
if(!nameCheck()) {
isValid = false;
}
if(!phoneCheck()) {
isValid = false;
}
if (isValid === false) {
$('#error').html(errorNotify).hide().slideDown('slow');
for (var i = 0; i < errorField.length; i++) {
$(errorField[i]).addClass('error');
}
errorNotify = 'Sorry, we could not process your request because ';
}
function nameCheck(){
if ($('#name').val() === '') {
errorNotify += ' you did not enter your name.';
errorField.push($('#name'));
return false;
} else {
return true;
}
}
function phoneCheck(){
var phoneCheck = $('#phoneNumber').val();
if (phoneCheck === '') {
errorNotify += ' you did not enter your phone number.';
errorField.push($('#phoneNumber'));
return false;
} else if (phoneCheck.length !== 10) {
errorNotify += 'please enter a 10 digit phone number';
errorField.push($('#phoneNumber'));
}
else if (isNaN(parseInt(phoneCheck))) {
errorNotify += 'you have entered a letter, please enter a number';
errorField.push($('#phoneNumber'));
}
else {
return true;
}
}
return isValid;
}
$(function () {
$('#contact').submit(function() {
return formVal();
});
$('#sameInfo').change(function() {
if ($(this).is(":checked")) {
alert('this is a test');
} else {
alert('this is not a test');
}
});
});
Not that it should fail totally because of this, but you're missing return values on your else if's in the phoneCheck() function.
Other than that it looks fine imo.
Trying to get my final project ready on time (for once) but I cannot seem to get the radio-button group to validate when submitting the form. I have everything else working, and validation is so-so, however, the radio group is being stubborn. I've tried different ways such as removing the variable and pointing directly to the 'group1' but nothing has worked. Any help would be greatly appreciated.
<script type="text/javascript">
function ValidateContactForm()
{
var name = document.ContactForm.Name;
var email = document.ContactForm.Email;
var phone = document.ContactForm.areaCode;
var what = document.ContactForm.Subject;
var comment = document.ContactForm.Comment;
var btn = document.ContactForm.group1;
if (name.value == "")
{
window.alert("Please enter your name.");
name.focus();
return false;
}
if (email.value == "")
{
window.alert("Please enter a valid e-mail address.");
email.focus();
return false;
}
if (email.value.indexOf("#", 0) < 0)
{
window.alert("Please enter a valid e-mail address.");
email.focus();
return false;
}
if (email.value.indexOf(".", 0) < 0)
{
window.alert("Please enter a valid e-mail address.");
email.focus();
return false;
}
if (btn.value > 0) {
window.alert("Please choose method of contact.");
btn.focus();
return false;
}
if (phone.value == "")
{
window.alert("Please enter your telephone number.");
phone.focus();
return false;
}
if (what.selectedIndex < 1)
{
alert("Please tell us how we can help you.");
what.focus();
return false;
}
if (comment.value == "")
{
window.alert("Please provide a detailed description or comment.");
comment.focus();
return false;
}
}
function validateFixedLengthNumericField(numericField, len){
if (len != numericField.value.length){
numericField.focus();
alert('Field must contain exactly '+len+' numbers.');
}
}
function validateNextField(numericField, len, nextField){
if (len == numericField.value.length){
nextField.focus();
}
}
</script>
<form method="post" onSubmit="return ValidateContactForm();" name="ContactForm">
<div align="center">
<table border="2">
<tr>
<td valign="top"><h3 align="left">Contact Information</h3>
<p align="left">Name:<br /> <input type="text" size="65" name="Name"></p>
<p align="left">E-mail Address:<br /><input type="text" size="65" name="Email"></p>
<p align="left">Telephone:<br />
<div class="Telephone" style="float:left;">
(<input name="areaCode" id="areaCode" type="text" maxlength="3"
onkeyup="validateNextField(this,3,phonePrefix);"
onblur="validateFixedLengthNumericField(this,3);"
style="font-size:11px; width:20px;" title="Area Code" autocomplete="off">)
<input name="phonePrefix" id="phonePrefix" type="text"
onkeyup="validateNextField(this,3,phoneSuffix);"
onblur="validateFixedLengthNumericField(this,3);"
style="font-size:11px; width:20px;" maxlength="3" title="Phone Prefix" autocomplete="off">-
<input name="phoneSuffix" id="phoneSuffix" type="text" maxlength="4"
onkeyup="validateNextField(this,3,phoneExtension);"
onblur="validateFixedLengthNumericField(this,4);"
style="font-size:11px; width:25px;" title="Phone Suffix" autocomplete="off"></p>
</div>
<p align="left"> </p>
<p align="left"><strong>Would you like to sign up for one of our mailings?</strong> <br />
</p>
<div align="left">
<input type="checkbox" name="option" value="newsletter" />
Newsletters<br />
<input type="checkbox" name="option" value="events" />
Events<br />
<input type="checkbox" name="option" value="grando" />
Grand Openings<br />
<input type="checkbox" name="option" value="coupon" />
Coupons<br />
<input type="checkbox" name="option" value="other" />
Other</div>
<p align="left"><strong>How do you perfer us to contact you</strong><br />
</p>
<div align="left">
<input type="radio" name="group1" id="r1" value="1" />
Phone
<br />
<input type="radio" name="group1" id="r2" value="2" />
Email<br />
<input type="radio" name="group1" id="r3" value="3" />
Snail Mail
</div>
<p align="left">What can we help you with?
<select type="text" value="" name="Subject">
<option> </option>
<option>Customer Service</option>
<option>Question</option>
<option>Comment</option>
<option>Complaint</option>
<option>Other</option>
</select></p>
<p align="left">Comments:</p>
<p align="center">
<textarea cols="55" rows="10" name="Comment"></textarea>
</p>
<p align="center"><input type="submit" value="Send" name="submit"><input type="reset" value="Reset" name="reset">
</form>
In your case variable btn contains an array of radio buttons. So you need to loop through it and find which one is checked. Something like:
var somethingChecked = false;
for (i = 0; i < btn.length; i++) {
if (btn[i].checked) {
somethingChecked = true;
}
}
if (!somethingChecked) {
window.alert("Please choose method of contact.");
return false;
}