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;
}
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>
<form action="add.php" method="post" onsubmit="return ValidationEvent()">
<input type="email" placeholder="Email" class="js-email" name="email" value="<?=formDisplay(getSessionValue("er_email"))?>" required>
<input type="text" placeholder="Zip Code" class="js-zip" name="zip" value="<?=formDisplay(getSessionValue("er_zip"))?>" required>
<input type="text" placeholder="First Name" class="js-name" name="firstname" value="<?=formDisplay(getSessionValue("er_first"))?>" required>
<input type="text" placeholder="Last Name" class="js-lname" name="lastname" value="<?=formDisplay(getSessionValue("er_last"))?>" required>
<input type="password" id="password" placeholder="Password" class="js-pass" name="password" required>
<input type="password" id="confirm" placeholder="Confirm Password" class="js-pass" name="confirm" required>
<span class="textLeft flex alignCenter terms">
<input type="checkbox" name="terms" value="yes" required>
<span>
<span>I agree</span>
</span>
</span>
<span class="textLeft flex alignCenter terms">
<input type="checkbox" name="term" value="yes">
<span>
<span>Keep me posted</span>
</span>
</span>
<center>
<input class="disabled white cbtn1 c1" type="submit" id="submit-btn" value="START MY ORDER" disabled>
</center>
<?php
unset($_SESSION['er_email']);
unset($_SESSION['er_zip']);
unset($_SESSION['er_first']);
unset($_SESSION['er_last']);
?>
</form>
Javascript:
(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#submit-btn').attr('disabled', 'disabled').addClass('disabled').removeClass('orangeBtn');
} else {
$('#submit-btn').removeAttr('disabled').removeClass('disabled').addClass('orangeBtn');;
}
});
})()
As you can see from the image, the button gets enabled once you enter all the input fields, I tried with my javascript above for it to also be display until I check "I agree", even if the "keep me posted" was unchecked, but for some reason the it gets enabled before the user clicks "I agree" , how can I fix this?
if empty or checkbox not checked keep it disabled.
if (empty || !$('input[name="terms"]').is(':checked')) {
$('#submit-btn').attr('disabled', 'disabled').addClass('disabled').removeClass('orangeBtn');
} else {
$('#submit-btn').removeAttr('disabled').removeClass('disabled').addClass('orangeBtn');;
}
You are checking if inputs have values. the checkbox has a value "Yes" so it validates as true.
this is because you have skipped if checkbox is checked or not, so you have to add that check too:
var checkbox = $('form > input[type=checkbox]:checked').length;
$('form > input').each(function() {
if ($(this).val() == '' && checkbox == 0 ) {
empty = true;
}
});
This is simple example of how to enable and disable a button.
This might help you implement your logic.
$("#testCheckBox").click(function(){
if(this.checked) {
$("#testBtn").removeAttr("disabled");
} else {
$("#testBtn").prop("disabled", true);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="checkbox" id="testCheckBox">
<button id="testBtn" disabled="true">Click It</button>
I have created a web page using bootstrap. There are 2 text boxes and a button to submit. I have written JavaScript function to give an alert if any text field is empty. I am amazed to see that it is not working. My JavaScript function is:
function validateForm()
{
var a=document.forms["Form"]["field1"].value;
var b=document.forms["Form"]["field2"].value;
if(a=="" && b=="")
{
alert("Both fields are required");
return false;
}else if (a==null || a=="")
{
alert("Field 1 is required");
return false;
}else if (b==null || b=="")
{
alert("Field 2 is required");
return false;
}else if(a!="" && b!="")
{
alert("Submitted Successfully");
return true;
}
}
My form code is:
<form role="form" method="post" name="Form" onsubmit="return validateForm()">
<div class="row 150%">
<div class="6u 12u$(medium)">
<input class="form-control" name="field1" id="ex1" type="text" autofocus placeholder="First Text Field">
</div>
<div class="6u 12u$(medium)">
<input class="form-control" name="field2" id="ex2" type="text" autofocus placeholder="Second Text Field">
</div>
</div><br /><br />
<button id="submit" class="button" style="vertical-align:middle">
<span>Submit </span>
</button>
</form>
How have you included the validateForm javascript?
for instance the following works for me:
<html>
<body>
<script>
function validateForm()
{
var a=document.forms["Form"]["field1"].value;
var b=document.forms["Form"]["field2"].value;
if(a=="" && b=="")
{
alert("Both fields are required");
return false;
}else if (a==null || a=="")
{
alert("Field 1 is required");
return false;
}else if (b==null || b=="")
{
alert("Field 2 is required");
return false;
}else if(a!="" && b!="")
{
alert("Submitted Successfully");
return true;
}
}
</script>
<form role="form" method="post" name="Form" onsubmit="return validateForm()">
<div class="row 150%">
<div class="6u 12u$(medium)">
<input class="form-control" name="field1" id="ex1" type="text" autofocus placeholder="First Text Field">
</div>
<div class="6u 12u$(medium)">
<input class="form-control" name="field2" id="ex2" type="text" autofocus placeholder="Second Text Field">
</div>
</div><br /><br />
<button id="submit" class="button" style="vertical-align:middle">
<span>Submit </span>
</button>
</form>
</body>
</html>
How can I submit my form after satisfying my form validation function? I need it to redirect to my homepage. I'm thoroughly stumped. Is it possible to use an <input type="button"> instead of an <input type="submit"> to still submit the form? If not how could I use the submit button to first run my form validation function before submitting?
My HTML:
<form name="registerform" ID="registerform">
<div ID="Namebox">
<p>Name</p>
<input type="text" id="name" name="name" />
<br />
</div>
<br />
<div ID="emailbox">
<p>Email</p>
<input type="text" id="email" name="email" size="30"/>
<br />
</div>
<br />
<div ID="passwordbox">
<p>Password</p>
<input type="password" ID="password"/>
<br />
</div>
<br />
<div ID="confirmpasswordbox">
<p>Confirm Password</p>
<input type="password" ID="confirmpassword" onkeyup="passwordvalidator()"/>  <span id="doesnotmatch"></span>
<br />
</div>
<br />
<div ID="citystatebox">
<p>City, State</p>
<input type="text" id="citystate"name="citystate"/>
<br />
</div>
<br />
<br />
On-Snow Disciplines
<br />
<br />
  <input type="checkbox" name="onsnowdisciplines" value="Downhill Skiing"/> Downhill Skiing
<br />
  <input type="checkbox" name="onsnowdisciplines" value="Downhill Snowboarding"/> Downhill Snowboarding
<br />
  <input type="checkbox" name="onsnowdisciplines" value="Cross-Country Skiing"/> Cross-Country Skiing
<br />
  <input type="checkbox" name="onsnowdisciplines" value="Backcountry Skiing"/> Backcountry Skiing
<br />
  <input type="checkbox" name="onsnowdisciplines" value="Backcountry Snowboarding/Splitboarding"/> Backcountry Splitboarding
<br />
  <input type="checkbox" name="onsnowdisciplines" value="Park Skiing"/> Park Skiing
<br />
  <input type="checkbox" name="onsnowdisciplines" value="Park Riding"/> Park Riding
<br />
  <input type="checkbox" name="onsnowdisciplines" value="Ski Mountaineering"/> Ski Mountaineering
</p>
<br />
<br />
<input type="button" id="registerSubmitButton" onclick="regSubBut()" value="Send It">   <span id="errorInformer" style="color:red;"></span>
</form>
My JS:
function regSubBut() {
var error = document.getElementById("errorInformer");
var email = document.getElementById("email");
var emailFilter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (document.getElementById("name").value === "")
{
error.innerHTML = "Please enter a name";
document.getElementById("name").focus();
return false;
}
else if (email === "" || !emailFilter.test(email.value))
{
error.innerHTML = "Please enter a valid email";
email.focus();
return false;
}
else if (document.getElementById("password").value === "" || document.getElementById("confirmpassword").value === "")
{
error.innerHTML = "Please enter a password";
document.getElementById("password").focus();
return false;
}
else if (document.getElementById("citystate").value === "")
{
error.innerHTML = "Please enter a city and state";
document.getElementById("citystate").focus();
return false;
}
else {
return true;
var frm = document.getElementById("registerform");
frm.action = "Homepage.html";
frm.submit();
document.getElementById("welcomebutton").style.display = "block";
}
}
I see a problem with your code when there are no validation errors:
else {
return true;//below line won't execute, move it to the bottom
var frm = document.getElementById("registerform");
frm.action = "Homepage.html";
frm.submit();
document.getElementById("welcomebutton").style.display = "block";
}
You can use the onsubmit attribute of the form tag:
var valid = function() {
return false;
};
<form onsubmit="return valid();">
Won't submit ...
<input type="submit" />
</form>
You can also use the onclick attribute of the input tag:
var valid = function() {
return false;
};
<form>
Won't submit either ...
<input type="submit" onclick="return valid();" />
</form>
$('form')[0].checkValidity()
If above is executed assuming that you just have form element on this page this will perform validation ( HTML 5 validation ) and you don't need to use default submit.
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.