LaC0saNostra Posted February 28, 2014 Share Posted February 28, 2014 Hello everybody. I have been learning how to validate forms using JavaScript but I have never attempted this with checkboxes that I have. How do I set up validation for my checkboxes or what is the format to doing so? I have looked at some tutorials but I am still a little confused. My other validations work properly. Here is my code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Help Request</title> <link href="dynamic_form_and_html_validation.css" rel="stylesheet" type="text/css" /> <meta http-equiv="Content-Type" content ="text/html; charset=utf-8"/> <script type="text/javascript"> <!-- <! [CDATA[ function validateForm() { if (document.forms[0].Question.value == "") { alert ("Question field cannot be empty."); return false; } // end function if (document.forms[0].Details.value == "") { alert ("Details field cannot be empty."); return false; } // end function if (document.forms[0].CustName.value == "") { alert ("A name must be entered."); return false; } // end function } // ]]> --> </script> </head> <body> <div align="center"> <h1>Help Request</h1> </div> <p> Do you have any specific questions you would like to ask us? Please do not shy in being honest. We personally reply to every question asked because our team believes that the users are what keep us going. As always, thank you. </p> <form action="http://cdlwebsysdev.esc-atsystems.net/wsd/form-to-email.php" method="post" onsubmit="return validateForm();"> E-mail: <input type="hidden" name="ToAddress" value="LaC0saNostra11@gmail.com" /> <input type="hidden" name="CCAddress" value="" /> <input type="hidden" name="Subject" value="WSD: Assignmebnt 3.1-Help Request Form for Edward Schubauer" /> <input type="text" name="FromAddress" /> <table border="0" width="75%" align="left"> <tr> <td colspan="2">Question:<br /> <textarea rows="4" cols="60" name="Question" id="Question">Briefly describe your question here</textarea></td> </tr> <tr> <td colspan="2">Details:<br /> <textarea rows="12" cols="60" name="Details" id="Details">Fill in the details here. Please be specific as possible</textarea></td> </tr> <tr> <td colspan="2">Name*<br /> <textarea rows="1" cols="60" name="CustName" id="CustName"></textarea></td> </tr> <tr> <td colspan="2">Phone Number (optional)*<br /> <textarea rows="1" cols="60" name="CustNumber" id="CustNumber"></textarea></td> </tr> <tr> <td align="right"><input type="submit" value="Send" /></td> <td><input type="reset" value="Reset" /></td> </tr> </table> <br /> <br /> How can we contact you? <br /> <input type="checkbox" name="contact" value="E-mail" />E-mail<br /> <input type="checkbox" name="contact" value="Phone" />Phone Number<br /><br /> </form> <br /><br /><br /><br /><br /><br /> </body> </html> help_request_form.html Link to comment Share on other sites More sharing options...
scott100 Posted February 28, 2014 Share Posted February 28, 2014 (edited) see example here: http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_checkbox_order because you have 2 inputs with the same name (contact) <input type="checkbox" name="contact" value="E-mail" />E-mail<br /><input type="checkbox" name="contact" value="Phone" />Phone Number<br /><br /> you will need to use a for loop to cycle through the inputs function validateForm(){var contact = document.forms[0].contact; // Name of input elementvar count = 0; // count is zerofor (i=0;i<contact.length;i++) //loop through the contact checkboxes { if (contact[i].checked == true) // has the checkbox been ticked? { count += 1; // The checkbox has been ticked so add 1 to the count } } if (count == 0) // if count is still zero then nothings been ticked.{ alert("Please tick a contact box"); return false;}......... Edited February 28, 2014 by scott100 Link to comment Share on other sites More sharing options...
dsonesuk Posted February 28, 2014 Share Posted February 28, 2014 (edited) You should use .elements to loop through each form input element, consider adding a class that would identify it as being 'required', and add title to each input to use for alert warning message this is one i set up before, ages ago <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <script type="text/javascript"> /*<![CDATA[*//*---->*/ function validate_this_form(form_elem) { var parent_form = document.getElementById(form_elem.id); valid = true; var RadChkNameArray = new Array(); var RadChkGroupCount = 0; var RadChkNameCurrent = ""; var errormessage = ""; for (i = 0; i < parent_form.elements.length; i++) { var search_result = (parent_form.elements[i].className).indexOf("required"); if (parent_form.elements[i].type == "text" || parent_form.elements[i].type == "textarea") { if (parent_form.elements[i].value == parent_form.elements[i].defaultValue && search_result != -1 || parent_form.elements[i].value == "" && search_result != -1) { valid = false; highlightWarning01(parent_form.elements[i]) errormessage += "Please supply " + parent_form.elements[i].title + "n"; } } /* XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX CHECK required radio AND checkbox Elements XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX*/ // FIND required radio checkbox button group name reference and store in array if (parent_form.elements[i].type == "radio" && search_result != -1 || parent_form.elements[i].type == "checkbox" && search_result != -1) { if (parent_form.elements[i].name != RadChkNameCurrent) { RadChkNameArray[RadChkGroupCount] = parent_form.elements[i].name; RadChkselect = false; j = document.getElementsByName(RadChkNameArray[RadChkGroupCount]); for (l = 0; l < j.length; l++) { if (j[l].checked) { RadChkselect = true; } } if (!RadChkselect) { valid = false; for (l = 0; l < j.length; l++) { highlightWarning02(j[l].parentNode) } errormessage += "Please select an option from " + j[0].title + "n"; } RadChkGroupCount++; } RadChkNameCurrent = parent_form.elements[i].name; } } //finish for loop for looking through form elements /* XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX END of CHECK required radio AND checkbox Elements XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX*/ if (!valid) { alert(errormessage) } return valid; } function add_input_events(form_id) { input_list = document.getElementById(form_id); for (m = 0; m < input_list.length; m++) { if (input_list[m].type != "radio" && input_list[m].type != "checkbox") { input_list[m].onfocus = function() { //works for all inputs (including radio and checkbox) in other browser otherthan Chrome and Safari dehighlight(this) } } else { input_list[m].onclick = function() { // As Chrome and Safari only work with onclick for radio and checkbox use onclick for all browsers. dehighlight(this) } } } } /* XXXXXXXXXXXXXXXXXXX Highlight validation errors XXXXXXXXXXXXXXXXXX*/ var highlightWarningColor = "red"; function highlightWarning01(elem) { elem.style.borderColor = highlightWarningColor; elem.style.borderWidth = "1px"; } function highlightWarning02(elem) { elem.style.backgroundColor = highlightWarningColor; } /* XXXXXXXXXXXXXXXXXXX UN-Highlight validation errors XXXXXXXXXXXXXXXXXX*/ function dehighlight(elem) { j = document.getElementsByName(elem.name); for (l = 0; l < j.length; l++) { if (j[l].type == "text" || j[l].type == "textarea") { j[l].style.borderColor = ""; } else if (j[l].type == "radio" || j[l].type == "checkbox") { j[l].parentNode.style.backgroundColor = "transparent"; } } } window.onload = function() { add_input_events("myform") } /*--*//*]]>*/ </script> <style type="text/css"> input[type=text], textarea {border:1px solid #ccc; } input[type=radio], input[type=checkbox] {margin:0; float:left;} label {display: block;} .radio_style, .checkbox_style { display:inline-block; margin: 0; padding: 0 0 1px 1px; position: relative; top: 2px;} .checkbox_style { padding: 1px;} </style> </head> <body> <form action="#" method="post" id="myform" onsubmit="return validate_this_form(this)" > <div> <p> * denotes required</p> <label>First Name: *<input id="fname" name="fname" type="text" title="First Name" class="required testthis" /></label> <label>Last Name: *<input id="lname" name="lname" type="text" title="Last Name" class="required testthis" /></label> <label>Email Name: *<input id="email" name="email" type="text" title="Email Address" class="required testthis" /></label> <label>Address Name: <input id="address" name="address" type="text" title="Address" /></label> <label>Test1: *</label> <span class="radio_style"><input type="radio" name="test1[]" title="Test1" value="1" class="required testthis" /></span> <span class="radio_style"><input type="radio" name="test1[]" title="Test1" value="2" class="required testthis" /></span> <span class="radio_style"><input type="radio" name="test1[]" title="Test1" value="3" class="required testthis" /></span> <span class="radio_style"><input type="radio" name="test1[]" title="Test1" value="4" class="required testthis" /></span> <span class="radio_style"><input type="radio" name="test1[]" title="Test1" value="5" class="required testthis" /></span> <label>Test2:</label> <span class="radio_style"><input type="radio" name="test2[]" title="Test2" value="1" /></span> <span class="radio_style"><input type="radio" name="test2[]" title="Test2" value="2" /></span> <span class="radio_style"><input type="radio" name="test2[]" title="Test2" value="3" /></span> <span class="radio_style"><input type="radio" name="test2[]" title="Test2" value="4" /></span> <span class="radio_style"><input type="radio" name="test2[]" title="Test2" value="5" /></span> <label>Check 1: *</label> <span class="checkbox_style"><input name="check1[]" type="checkbox" class="required testthis" value="1" title="checkbox1" /></span> <span class="checkbox_style"><input name="check1[]" type="checkbox" class="required testthis" value="2" title="checkbox1" /></span> <span class="checkbox_style"><input name="check1[]" type="checkbox" class="required testthis" value="3" title="checkbox1" /></span> <span class="checkbox_style"><input name="check1[]" type="checkbox" class="required testthis" value="4" title="checkbox1" /></span> <label>TextArea 1: * <textarea name="textarea1" class="required testthis" title="Text Area1" style="width:100px; min-height: 4em;" cols="" rows="">some text is here!</textarea> </label> <label>TextArea 2: <textarea name="textarea2" title="Text Area2" style="width:100px; min-height: 4em;" cols="" rows="">Other text is here!</textarea> </label> <input type="submit" value="Submit Button" /> <input type="reset" value="Reset Button" /> </div> </form> </body></html> Edited February 28, 2014 by dsonesuk Link to comment Share on other sites More sharing options...
LaC0saNostra Posted March 6, 2014 Author Share Posted March 6, 2014 Guys thank you so much for the advice. I actually went with the for loop and got it to work in my page perfectly. Scott100 thank you for showing me exactly how this is done. Also dsonesuk thank you for your perspective as well on this. Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now