I can't seem to figure out the proper JavaScript to validate this form. Please help/provide feedback!
Essentially, my script should validate whether the user has entered data in the input text box, has checked a radio button, has checked at least one checkbox, and has selected an option from the select items.
Also the form uses a submit button to invoke the validation script, so that the form is processed only when the form fields are validated and accepted. If a field is invalid then display a message to the user.
Also need to make sure the form doesn't automatically reset every time the user gets a validation error.
<body>
<section>
<h1 style="text-align: center">Vacation Interest Vote Form</h1>
<form name="VacayForm" action="mailto:" onsubmit="return Validate1()" method="post">
<p>Name:<input type="text" name="name" size="25"></p><br>
<p>Do You Prefer an international destination?</p>
<p>Domestic<input type="radio" name="domint" value="domestic"></p>
<p>International<input type="radio" name="domint" value="international"></
<br>
<p>Where would you like to go?</p>
<select type="text" name="continent" value="select" size="1">
<option value="domestic">Domestic</option>
<option value="europe">Europe</option>
<option value="camerica">Central America</option>
<option value="asia">Asia</option>
<option value="aus">Australia</option>
</select>
<br>
<p>Check the box to act as your digital signature to cast your vote
<input type="checkbox" value="agree" name="sig">
<input type="submit" value="Send" name="submit" onclick="if(!this.form.sig.checked){alert('You must agree to cast your vote by checking the box.');
return false}">
<input type="reset" value="Reset"name="reset">
</form>
</section>
<script>
function Validate1() {
var nam = document.forms["VacayForm"]["name"];
var dom = document.forms["VacayForm"]["domestic"];
var int = document.forms["VacayForm"]["international"];
var sel = document.forms["VacayForm"]["select"];
var agree = document.forms["VacayForm"]["agree"];
//if (name.value == "")
//{
// window.alert("Please enter your name.");
// name.focus();
// return false;
//}
if( document.VacayForm.name.value == "" )
{
alert( "Please provide your name!" );
document.VacayForm.name.focus() ;
return false;
}
if (domestic.value == "")
else (international.value == "")
{
window.alert("Please select domestic or international preference to proceed.");
domestic.focus();
international.focus();
return false;
}
if (select.selectedIndex < 1)
{
alert("Please select where you prefer to visit");
select.focus();
return false;
}
return true;
}
//function Validate2() {
// var radios = document.getElementsByName("yesno");
// var formValid = false;
// var i = 0;
// while (!formValid && i < radios.length) {
// if (radios[i].checked) formValid = true;
// i++;
// }
// if (!formValid) alert("Must check an option!");
// return formValid;
//}
</script>
</body>
</html>
Your validate function could look like this...
function validate() {
var form = document.forms.VacayForm;
var name = form.name;
var domInt = form.domint;
var continent = form.continent;
var agree = form.agree;
if (!name.value) {
alert( "Please provide your name!" );
name.focus();
return false;
}
if (!domInt.value) {
alert( "Please select domestic or international preference to proceed" );
domInt.focus();
return false;
}
if (!continent.value) {
alert("Please select where you prefer to visit");
continent.focus();
return false;
}
if (!agree.checked) {
alert("Please check agree to continue");
agree.focus();
return false;
}
return true;
}
This article from Javascript.info website teaches how to use forms and form elements...
Related
I am unable to stop the form from submitting when any of the inputs are blank. It's not erroring out, but it's also not stopping the submit. I have the function being called in the form submit input. It is under the onClick call.
JS File
function stopSubmit(){
var inDay = document.getElementById(indate).value;
var inType = document.getElementById(intype).value;
var inAmount = document.getElementById(inamount).value;
if (inDay == "") {
alert("Please select a date");
return false;
}
if (inType == "Select One"){
alert("Please select a frequency");
return false;
}
if (inAmount == ""){
alert("Please enter an amount");
return false;
}
else {
alert("Your form was submitted");
}
}
HTML File
<td>
<input type="submit" name="submitincome" value="submit" onclick="stopSubmit()">
</td>
Edit
Use the required attribute and you won't even need any JavaScript. See demo 2. for a functioning demo see this PLUNKER
OLD
Before each return false add e.preventDefault()
Demo (Does not function due to SO security measures)
function stopSubmit(e) {
var inDay = document.getElementById(indate).value;
var inType = document.getElementById(intype).value;
var inAmount = document.getElementById(inamount).value;
if (inDay == "") {
alert("Please select a date");
e.preventDefault();
return false;
}
if (inType == "Select One") {
alert("Please select a frequency");
e.preventDefault();
return false;
}
if (inAmount == "") {
alert("Please enter an amount");
e.preventDefault();
return false;
} else {
alert("Your form was submitted");
}
}
<form>
<td>
<input type="submit" name="submitincome" value="submit" onclick="stopSubmit()">
</td>
</form>
Demo 2 Use the required attribute
<!DOCTYPE html>
<html>
<head>
<style>
input {
display: block
}
</style>
</head>
<body>
<form id='inform' action='http://httpbin.org/post' method='post'>
<input id='indate' name='indate' required>
<input id='intype' name='intype' required>
<input id='inamount' name='inamount' required>
<input type="submit">
</form>
</body>
</html>
I was able to see where you doing the mistake, document.getElementById() takes in a string as the parameter but you happen to be passing an undefined variable
function stopSubmit(){
var inDay = document.getElementById('indate').value;
var inType = document.getElementById('intype').value;
var inAmount = document.getElementById('inamount').value;
if (inDay === "") {
alert("Please select a date");
return false;
}
if (inType == "Select One"){
alert("Please select a frequency");
return false;
}
if (inAmount === ""){
alert("Please enter an amount");
return false;
}
else {
alert("Your form was submitted");
}
}
Hi I'm trying to make this code more clean. I struggle with arrays and loops and have no idea how to convert this into into a loop. This is javascript for a form on an html page and if they leave a field blank, when they hit submit it should return an alert box and if everything is submitted properly it should confirm with them. There's also a reg exp for an acceptable postal code entry.
function validate()
{
var register = document.forms[0];
if (register.fname.value === "")
{
alert("Please fill out your first name.");
return false;
}
else if(register.lname.value === "")
{
alert("Please fill out your last name.");
return false;
}
else if(register.address.value === "")
{
alert("Please fill out your address.");
return false;
}
else if(register.postal.value ==="")
{
alert("Please enter a valid postal code.");
return false;
}
else if(!checkPostal(register.postal.value))
{
alert("Please enter a valid postal code.");
return false;
}
else if(register.eAddress.value === "")
{
alert("Please fill out your email address.");
return false;
}
return confirm("Is the information correct?");
}
//postal code regExp
function checkPostal()
{
var myReg = /^[A-Z]\d[A-Z] ?\d[A-Z]\d$/ig;
return myReg.test(document.getElementById("postal").value);
}
You can make this a pure HTML solution if you want to reduce javascript:
inputs have a required attr ref
additionally, inputs have a pattern attr ref that supports regex.
This kind of solution lets the browser handle feedback
<form>
<label>first name:
<input type="text" name="fname" required
minlength="1">
</label><br/>
<label>last name:
<input type="text" name="lname" required
minlength="1">
</label><br/>
<label>postal code:
<input type="text" name="zip" required pattern="^[A-Z]\d[A-Z] ?\d[A-Z]\d$"
minlength="1">
</label><br/>
<input type="submit" />
</form>
$.each( $( "#input input" ), function( key, element ) {
if( !$(element).val() ) {
$( "#error" + key ).text( "Input " + $( element ).attr( "name" ) + " is required");
return false;
}
});
Set your message as attribute on each element of the form like this:
<form method="POST" action="submit.php">
<input id="item1" type="text" value="" data-message="My error message" data-must="true">
...//do the same for other elements...
</form>
Now loop like below
var elements = document.forms[0].elements;
for (var i = 0, element; element = elements[i++];) {
if (element.getAttribute("must") && element.value === ""){
alert(element.getAttribute("message"));
return false;
}
}
return confirm("Is the information correct?");
I have a form with text fields, a drop down list, radio buttons, and text boxes. I would like to show all user input from the form in an alert. This was working before but then I was required to add the drop down menu. Now, upon clicking submit no alert shows up. I would like the alert to print out all information entered into the form by the user, including the selection from the drop down menu.
This is what I have:
<html>
<!--nff Add a title to the Web Page.-->
<head>
<title>Pizza Order Form</title>
<script>
/*nff Add the doClear function to clear the information entered by the user and enter the information to be cleared when the clear entries button is clicked at the bottom of the Web Page.*/
function doClear()
{
var elements = document.getElementsByTagName('select');
elements[0].value = 'PA';
document.PizzaForm.customer.value = "";
document.PizzaForm.address.value = "";
document.PizzaForm.city.value = "";
document.PizzaForm.zip.value = "";
document.PizzaForm.phone.value = "";
document.PizzaForm.email.value = "";
document.PizzaForm.sizes[0].checked = false;
document.PizzaForm.sizes[1].checked = false;
document.PizzaForm.sizes[2].checked = false;
document.PizzaForm.sizes[3].checked = false;
document.PizzaForm.toppings[0].checked = false;
document.PizzaForm.toppings[1].checked = false;
document.PizzaForm.toppings[2].checked = false;
document.PizzaForm.toppings[3].checked = false;
document.PizzaForm.toppings[4].checked = false;
document.PizzaForm.toppings[5].checked = false;
document.PizzaForm.toppings[6].checked = false;
document.PizzaForm.toppings[7].checked = false;
document.PizzaForm.toppings[8].checked = false;
return;
}
//nff Add a doSubmit button to indicate what the outcome will be when the user clicks the submit order button at the bottom of the form.
function doSubmit()
/*nff Add an if statement to the doSubmit function to return false if there is missing information in the text fields once the user clicks the submit order button.*/
{
if (validateText() == false) {
return false;
}
//nff Add an if statement to the doSubmit function to return false if there is no pizza size selected using the radio buttons.
if (validateRadio() == false) {
return false;
}
//nff Add an if statement to the doSubmit function to return false if there are no toppings selected using the checkboxes.
if (validateCheckbox() == false) {
return false;
}
//nff Add an if statement to the doSubmit function to return false if the email entered by the user is empty or does not fit the acceptable format.
if (validateEmail() == false) {
return false;
}
/*nff Add an if statement to the doSubmit function to return false if the phone number entered by the user is empty or does not fit the acceptable formats.*/
if (validatePhone() == false) {
return false;
}
//nff Add an alert box to show customer information from text fields when the Submit Order button is clicked.
var customer = document.PizzaForm.customer.value;
var address = document.PizzaForm.address.value;
var city = document.PizzaForm.city.value;
var state = document.PizzaForm.state.value;
var zip = document.PizzaForm.zip.value;
var phone = document.PizzaForm.phone.value;
var email = document.PizzaForm.email.value;
var size = "";
for (var i = 0; i < document.PizzaForm.sizes.length; i++) {
if (document.PizzaForm.sizes[i].checked) {
size = document.PizzaForm.sizes[i].nextSibling.nodeValue.trim();
break;
}
}
var toppings = [];
for (var i = 0; i < document.PizzaForm.toppings.length; i++) {
if (document.PizzaForm.toppings[i].checked) {
toppings.push(document.PizzaForm.toppings[i].nextSibling.nodeValue.trim());
}
}
alert("Name: " + customer + '\n' +
"Address: " + address + '\n' +
"City: " + city + '\n' +
"State: " + state + '\n' +
"Zip: " + zip + '\n' +
"Phone: " + phone + '\n' +
"Email: " + email + '\n' +
"Size: " + size + '\n' + (toppings.length ? 'Toppings: ' + toppings.join(', ') : ''));
}
//nff Add the validateText function to ensure that all text fields are complete before the order is submitted.
function validateText() {
var customer = document.PizzaForm.customer.value;
if (customer.length == 0) {
alert('Name data is missing');
document.PizzaForm.customer.focus();
return false
};
var address = document.PizzaForm.address.value;
if (address.length == 0) {
alert('Address data is missing');
return false;
}
var city = document.PizzaForm.city.value;
if (city.length == 0) {
alert('City data is missing');
return false;
}
var zip = document.PizzaForm.zip.value;
if (zip.length == 0) {
alert('Zip code data is missing');
} else if (zip.length < 5) {
alert('Invalid zip code data');
} else {
return false;
}
var phone = document.PizzaForm.phone.value;
if (phone.length == 0) {
alert('Phone data is missing');
return false;
}
var email = document.PizzaForm.email.value;
if (email.length == 0) {
alert('Email data is missing');
return false;
}
return true;
}
//nff Add the validateRadio function so that if none of the radio buttons for pizza size are selected it will alert the user.
function validateRadio() {
if (document.PizzaForm.sizes[0].checked) return true;
if (document.PizzaForm.sizes[1].checked) return true;
if (document.PizzaForm.sizes[2].checked) return true;
if (document.PizzaForm.sizes[3].checked) return true;
alert('Size of pizza not selected');
document.PizzaForm.sizes[0].foucs();
return false;
}
//nff Add the validateCheckbox function so that if none of the checkboxes for toppings are selected it will alert the user.
function validateCheckbox() {
if (document.PizzaForm.toppings[0].checked) return true;
if (document.PizzaForm.toppings[1].checked) return true;
if (document.PizzaForm.toppings[2].checked) return true;
if (document.PizzaForm.toppings[3].checked) return true;
if (document.PizzaForm.toppings[4].checked) return true;
if (document.PizzaForm.toppings[5].checked) return true;
if (document.PizzaForm.toppings[6].checked) return true;
if (document.PizzaForm.toppings[7].checked) return true;
if (document.PizzaForm.toppings[8].checked) return true;
alert ('Toppings are not selected');
return false;
}
//nff Add the validateEmail function to ensure that the email address has been entered in the correct format.
function validateEmail() {
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{3,4})+$/.test(PizzaForm.email.value))
{
return (true)
}
alert("You have entered an invalid email address")
return (false)
}
//nff Add the validatePhone function to ensure that the phone number has been entered in any of the acceptable formats.
function validatePhone() {
if (/^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{4}$/.test(PizzaForm.phone.value))
{
return (true)
}
alert("You have entered an invalid phone number")
return (false)
}
</script>
</head>
<body>
<!--nff Add a form for the user to enter information into.-->
<form name="PizzaForm">
<!--nff add a title at the top of the Web Page-->
<h1>The JavaScript Pizza Parlor</h1>
<!--nff add directions to the user for the information to be entered-->
<p>
<h4>Step 1: Enter your name, address, and phone number:</h4>
<!--nff change the font-->
<font face="Courier New">
<!--nff insert a text field for user to enter their name, add spaces between the title of the text box and the box itself, specify the size of the input box, and the type of input into the box as text.-->
<form>
Name: <input name="customer" size="50" type="text"><br>
<!--nff insert a text field for user to enter their address, specify the size of the input box, and the type of input into the box as text.-->
Address: <input name="address" size="50" type="text"><br>
<!--nff Insert a text field for user to enter their city, add spaces between the title of the text box and the box itself, specify the size of the input box, and the type of input into the box as text.-->
City: <input name="city" size="15" type="text">
State:<select>
<option selected value="PA">PA</option>
<option value="NJ">NJ</option>
<option value="NY">NY</option>
<option value="DE">DE</option>
</select>
Zip: <input name="zip" size="5" type="text"><br>
<!--nff Insert a text field for the user to enter their phone number, insert spaces after the title of the box, specify the size of the box, and the type of input as text.-->
Phone: <input name="phone" size="50" type="text"><br>
<!--nff Insert a text field for the user to enter their email address, insert spaces after the title of the box, specify the size of the box, and the type of input as text.-->
Email: <input name="email" size="50" type="text"><br>
</font>
</p>
<!--nff add second step to order a pizza-->
<p>
<h4>Step 2: Select the size of pizza you want:</h4>
<font face="Courier New">
<!--nff Add radio buttons to choose from four options for pizza sizes.-->
<input name="sizes" type="radio">Small
<input name="sizes" type="radio">Medium
<input name="sizes" type="radio">Large
<input name="sizes" type="radio">Jumbo<br>
</font>
</p>
<p>
<!--nff add third step to order a pizza-->
<h4>Step 3: Select the pizza toppings you want:</h4>
<font face="Courier New">
<!--nff Add check boxes for user to choose toppings.-->
<input name="toppings" type="checkbox">Pepperoni
<input name="toppings" type="checkbox">Canadian Bacon
<input name="toppings" type="checkbox">Sausage<br>
<input name="toppings" type="checkbox">Mushrooms
<input name="toppings" type="checkbox">Pineapple
<input name="toppings" type="checkbox">Black Olives<br>
<input name="toppings" type="checkbox">Green Peppers
<input name="toppings" type="checkbox">Extra Cheese
<input name="toppings" type="checkbox">None<br>
</font>
</p>
<!--nff Add buttons for the options to submit order or clear entries. Add an onClick event to show one of the alerts entered earlier in this document when the submit button is clicked at the bottom of the Web Page. Add and onClick event to clear the entries in this form upon clicking the clear entries button.-->
<input type="button" value="Submit Order" onClick="doSubmit()">
<input type="button" value="Clear Entries" onClick="doClear()">
</form>
</body>
</html>
Please show your HTML/Form also.
Please read about the .selectedIndex property for drop-down list.
One quick link below:
http://www.w3schools.com/jsref/prop_select_selectedindex.asp
Your < select > has no name, so when you are trying to retrieve the value of state, you get nothing.
Try this:
<select name="state">
<option selected value="PA">PA</option>
<option value="NJ">NJ</option>
<option value="NY">NY</option>
<option value="DE">DE</option>
</select>
I am trying to have a select drop down with about 25 options certain choices that are picked will make another textbox field appear and be required. I tried making it grayed out and always there but since nothing was entered it was still required and would not process.
Now I have changed it to read-only and just wrote Not Required in the box since its filled out it would accept if its a required field.
But I really would like to learn how to make it just appear when that option is selected and once it appears make it required so the user can not go onto the next page until it is filled out.
(If you choose pickup or truck it is required)
So basically Dropdown makes textbox appear and required and not required when it is not showing
Does anyone have any ideas of how I could do this?
http://jsfiddle.net/of1sdq11/
function GVW(){
var dropdown1 = document.getElementById('vehiclebody');
var textbox = document.getElementById('gvw');
if(dropdown1.selectedIndex == 0){
textbox.value = "";
document.getElementById("gvw").readOnly = false;
}
else if(dropdown1.selectedIndex == 1) {
textbox.value = "NOT REQUIRED";
document.getElementById("gvw").readOnly = true;
}
else if(dropdown1.selectedIndex == 2) {
textbox.value = "";
document.getElementById("gvw").readOnly = false;
}
else if(dropdown1.selectedIndex == 3) {
textbox.value = "NOT REQUIRED";
document.getElementById("gvw").readOnly = true;
}
else if(dropdown1.selectedIndex == 4) {
textbox.value = "";
document.getElementById("gvw").readOnly = false;
}
else if(dropdown1.selectedIndex == 5) {
textbox.value = "NOT REQUIRED";
document.getElementById("gvw").readOnly = true;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select name="vehiclebody" id="vehiclebody" required="yes" message="Please select body." size="1" onChange="GVW();">
<option value="">Choose a Vehicle</option>
<option value="0">2Dr</option>
<option value="1">Pickup</option>
<option value="2">4dr</option>
<option value="3">Truck</option>
<option value="4">Convertible</option>
<option value="5">Van</option>
</select>
<input type="text" name="gvw" id="gvw" onfocus="this.select()" message="Please enter gross vehicle weight." value="">
If I am understanding you correctly, you want to make it so the textbox doesn't even show unless it is required. I modified the code a bit so that you don't need the list of if statements. By making an array that corresponds to the selectedIndex, you can just check the property!
Find the jsFiddle here: http://jsfiddle.net/of1sdq11/19/
First, I made the textbox start hidden. If the display is set to none, it will not be submitted with the form. If display is anything other than none, it will display and submit with the form. If you just wanted an invisible field that was always submitted, you would use visibility set to hidden instead!
<input type="text" name="gvw" id="gvw" onfocus="this.select()" message="Please enter gross vehicle weight." value="" style="display:none;">
Then I modified your code to show the textbox if the properties match. Now all you have to do is set whether required is true or false in the "is_required" variable to match the corresponding selectedIndex and it should work.
function GVW(){
var dropdown1 = document.getElementById('vehiclebody');
var textbox = document.getElementById('gvw');
// Array for storing whether the textbox is required
var is_required = [false, true, false, true, false, true];
// If dropdown1.selectedIndex is 0, it will pull the value from the 0 slot
// of the is_required array
if(is_required[dropdown1.selectedIndex]) {
textbox.required = true;
textbox.style.display = "inline-block";
} else {
textbox.value = "";
textbox.required = false;
textbox.style.display = "none";
}
}
Now on whatever page you are submitting to, you can just check to see if the textbox even existed in the form submission, and if it did, get the data, otherwise skip it!
jQuery Version With Modifications
After further discussion with the OP, I rewrote this to work with all jQuery, along with adding the ability to hide a label in addition. I thought that others may find it helpful, so I wanted to post it here. Find the fiddle here: http://jsfiddle.net/of1sdq11/26/
The HTML
<select name="vehiclebody" id="vehiclebody" required="yes" message="Please select body." size="1">
<option value="">Choose a Vehicle</option>
<option value="0">2Dr</option>
<option value="1">Pickup</option>
<option value="2">4dr</option>
<option value="3">Truck</option>
<option value="4">Convertible</option>
<option value="5">Van</option>
</select>
<div style="display:inline;">
<label for="gvw" style="display:none;"> Gross Vehicle Weight:*</label>
<input type="text" name="gvw" id="gvw" onfocus="this.select()" message="Please enter gross vehicle weight." value="" style="display:none;">
<p style="display:none;">*Gross Vehicle Weight is required for heavy trucks over 5000 lbs. Visit our website for more information. Heavy Truck Information and Fee Schedule based on GVW </p>
</div>
The jQuery
$(function() {
$('#vehiclebody').change(function() {
var selected_index = $(this).find(":selected").index();
var textbox = $('#gvw');
var label = textbox.siblings('label');
var paragraph = textbox.siblings('p');
// Array for storing whether the textbox is required
var is_required = [false, true, false, true, false, true];
// If dropdown1.selectedIndex is 0, it will pull the value from the 0 slot
// of the is_required array
if(is_required[selected_index]) {
textbox.attr("required", "true");
textbox.show();
label.show();
paragraph.show();
} else {
textbox.val("");
textbox.attr("required", "false");
textbox.hide();
label.hide();
paragraph.hide();
}
});
});
Here's what you need. Check this fiddle
http://jsfiddle.net/of1sdq11/15/
<select name="vehiclebody" id="vehiclebody" required="yes" message="Please select body." size="1" onChange="GVW();">
<option value="">Choose a Vehicle</option>
<option value="0">2Dr</option>
<option value="1">Pickup</option>
<option value="2">4dr</option>
<option value="3">Truck</option>
<option value="4">Convertible</option>
<option value="5">Van</option>
</select>
<input type="text" name="gvw" id="gvw" onfocus="this.select()" message="Please enter gross vehicle weight." value="" hidden>
.
function GVW(){
var dropdown1 = document.getElementById('vehiclebody');
var textbox = document.getElementById('gvw');
if(dropdown1.selectedIndex == 0){
textbox.value = "";
document.getElementById("gvw").hidden = false;
document.getElementById("gvw").required = "yes";
}
else if(dropdown1.selectedIndex == 1) {
textbox.value = "NOT REQUIRED";
document.getElementById("gvw").hidden = true;
document.getElementById("gvw").required = "no";
}
else if(dropdown1.selectedIndex == 2) {
textbox.value = "";
document.getElementById("gvw").hidden = false;
document.getElementById("gvw").required = "yes";
}
else if(dropdown1.selectedIndex == 3) {
textbox.value = "NOT REQUIRED";
document.getElementById("gvw").hidden = true;
document.getElementById("gvw").required = "no";
}
else if(dropdown1.selectedIndex == 4) {
textbox.value = "";
document.getElementById("gvw").hidden = false;
document.getElementById("gvw").required = "yes";
}
else if(dropdown1.selectedIndex == 5) {
textbox.value = "NOT REQUIRED";
document.getElementById("gvw").hidden = true;
document.getElementById("gvw").required = "no";
}
}
I've searched high and low for the answer to this but can't find it anywhere.
I have a form which has the HTML 'required' attributes and it does a fine job of highlighting the fields that need to filled in before submission...or would do, but the system which my form is bolted onto (of which I have no control over) submits the form anyway after a few seconds. It relies on Javascript for it's submission. Therefore I'd like to write a Javascript script to check all fields for a required attribute. Currently I have a script that specifies the fields I want to be mandatory, but if it could look up the attribute instead, that would be brilliant.
In case that input[type=submit] is used, you don't need any JavaScript
<form id="theForm" method="post" acion="">
<input type="firstname" value="" required />
<input type="lastname" value="" required />
<input type="submit" name="submit" value="Submit" />
</form>
Working jsBin
But if input[type=button] is used for submitting the form, use the snippet below
<form id="theForm" method="post" acion="">
<input type="firstname" value="" required />
<input type="lastname" value="" required />
<input type="button" name="button" value="Submit" />
</form>
window.onload = function () {
var form = document.getElementById('theForm');
form.button.onclick = function (){
for(var i=0; i < form.elements.length; i++){
if(form.elements[i].value === '' && form.elements[i].hasAttribute('required')){
alert('There are some required fields!');
return false;
}
}
form.submit();
};
};
Wotking jsBin
Many years later, here is a solution that uses some more modern Javascript:
for (const el of document.getElementById('form').querySelectorAll("[required]")) {
if (!el.reportValidity()) {
return;
}
}
See Vlad's comment for a link to the Constraint Validation API (thanks Vlad, that helped!)
You can use Constraint validation API, which is supported by most browsers.
I'm late to the party but this worked for me.
<input type="firstname" value="" required />
document.getElementById('theForm').reportValidity();
if (check) {
//success code here
return true;
}
Credit to Vlad and a.l.e for pointing me in the right direction with their previous answers. This is a simplified version of their approach.
this will be validating all your form field types
$('#submitbutton').click(function (e) {
e.preventDefault();
var form = document.getElementById("myForm");
var inputs = form.getElementsByTagName("input"), input = null, select = null, not_pass = false;
var selects = form.getElementsByTagName("select");
for(var i = 0, len = inputs.length; i < len; i++) {
input = inputs[i];
if(input.type == "hidden") {
continue;
}
if(input.type == "radio" && !input.checked) {
not_pass = true;
}
if(input.type == "radio" && input.checked){
not_pass = false;
break;
}
if(input.type == "text" && !input.value) {
not_pass = true;
}
if(input.type == "text" && input.value){
not_pass = false;
break;
}
if(input.type == "number" && !input.value) {
not_pass = true;
}
if(input.type == "number" && input.value){
not_pass = false;
break;
}
if(input.type == "email" && !input.value) {
not_pass = true;
}
if(input.type == "email" && input.value){
not_pass = false;
break;
}
if(input.type == "checkbox" && !input.checked) {
not_pass = true;
}
if(input.type == "checkbox" && input.checked) {
not_pass = false;
break;
}
}
for(var i = 0, len = selects.length; i < len; i++) {
select = selects[i];
if(!select.value) {
not_pass = true;
break;
}
}
if (not_pass) {
$("#req-message").show();//this div # in your form
return false;
} else {
//do something here
}
});
If using either the simple "required" solution above or the "Constraint Validation API" solution, how do you make a select option required if it is contingent on another select field having a certain answer. I used the "required" method as you can see below which works great for Country select.
<select id="country_code" name="country_code" required>
<option value="">--None--</option>
<option value="AL">Albania</option>
<option value="US">United States</option>
</select>
<script>
$("select[name='country_code']").change(function() {
if ($(this).val() == "US") {
$("select[name='state_code'] option").removeClass('hidden');
$("select[name='state_code'] option").addClass('required');
} else {
} else {
$("select[name='state_code'] option").addClass('hidden');
}
});
</script>
<label for="state_code">State/Province</label>
<select id="state_code" name="state_code">
<option value="">--None--</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
</select>
As you can see, I tried adding the class "required" to State select if Country select is US, but it didn't do anything.