JavaScript - Validate Checkboxes
I have a group of checkboxes named "list[]". I want to validate that at least one is checked. How can I do this?
Similar TutorialsCan someone please help, I don't understand why my code doesn't work?! I just want to check to see if a checkbox has been checked... Code: <script language="JAVASCRIPT" type="text/djs"> function checkCheckBoxes() { if (document.f1.Times[].checked == false { alert ('You didn\'t choose any of the checkboxes!'); return false; } else { return true; } } </script> <form onsubmit="return checkCheckBoxes();" action="add-booking-script.php" name="f1" method="post"> <input type="checkbox" name="Times[]" value="07:00:00"> 07:00 - 10:00<br /> <input type="checkbox" name="Times[]" value="10:00:00"> 10:00 - 13:00<br /> <input type="checkbox" name="Times[]" value="13:00:00"> 13:00 - 16:00<br /> <input type="checkbox" name="Times[]" value="16:00:00"> 16:00 - 19:00<br /> </form> Hello all, I have a form that submits a POST request when data is submitted. A Servlet then processes this POST request and a JavaBean is used to make some calculations. The HTML response is not generated within the Servlet but instead I forward the request to a JSP to generate the response. - This all works fine, thankfully. However, I am stupidly suck trying to validate the form on the client side with a JavaScript function before the form is submitted. Here is my index.jps: Code: <%-- Document : index Created on : 19-Nov-2009, 13:41:30 Author : lk00043 --%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/JavaScript"> <!-- Start hiding JavaScript Statements function validateForm() { var student; var score1, score2, score3, score4; student = document.getElementById('student'); s1 = document.getElementById('score1'); s2 = document.getElementById('score2'); s3 = document.getElementById('score3'); s4 = document.getElementById('score4'); score1 = parseInt(s1.value); score2 = parseInt(s2.value); score3 = parseInt(s3.value); score4 = parseInt(s4.value); if(student.value.length == 0) { document.getElementById('StudentError1').innerHTML = " Enter a student name!"; return false; } if ((isNaN(score1)) || (score1 < 0) || (score1 > 100)) { document.getElementById('Error1').innerHTML = " Enter a number between 0 and 100!"; return false; } if ((isNaN(score2)) || (score2 < 0) || (score2 > 100)) { document.getElementById('Error2').innerHTML = " Enter a number between 0 and 100!"; return false; } if ((isNaN(score3)) || (score3 < 0) || (score3 > 100)) { document.getElementById('Error3').innerHTML = " Enter a number between 0 and 100!"; return false; } if ((isNaN(score4)) || (score4 < 0) || (score4 > 100)) { document.getElementById('Error4').innerHTML = " Enter a number between 0 and 100!"; return false; } } // End hiding JavaScript Statements --> </script> <title>Lab Class 7 - Task 2</title> </head> <body> <h1>Lab Class 7</h1> <form name="collectgrades" action="AssessGrades" method="POST" onSubmit="validateForm()" > Name of Student: <input type="text" name="student" id="student"/><span id="StudentError1"> </span><br /> Presentation: <input type="text" name="score" id="score1"/><span id="Error1"> </span><br /> Writing style: <input type="text" name="score" id="score2"/><span id="Error2"> </span><br /> Technical content: <input type="text" name="score" id="score3"/><span id="Error3"> </span><br /> Depth of analysis: <input type="text" name="score" id="score4"/><span id="Error4"> </span><br /> Feedback:<select name="feedback" size="4" multiple="multiple"> <option>"Could be better structured."</option> <option>"Depth of analysis is good."</option> <option>"Very advanced material."</option> <option>"Very well structured."</option> </select><br /> <input type="submit" value="Submit" /> </form> </body> </html> Regardless of whether incorrect input is given, the data is still POSTed to the server and calculated on or a Server Side error is given. Am I correct in calling the function onClick? The validation essentially needs to be so that: - Student field contains a string - Score1, Score2, Score3 and Score 4 contain a number between 0 and 100 Any help is most appreciated, Cheers, Beetle. I am trying to create an onChange action that will validate that confirmation checkbox has been checked, and if not, popup an alert message and put the focus on the checkbox input and change the class of the container DIV to "highlight". Here is the form, with the 'onchange' trigger: Code: <form id="checkout" name="my_form" method="post" action="!---SCRIPT_NAME---" onsubmit="return validForm(this);"> <div id="verification" class="aligncenter required"> <input type="checkbox" id="verified" name="verified" value="" /> <label for="verified">YES</label>, the items and quantities shown above are correct.</div> <div class="required"><label for="name">Name:</label><input id="name" name="contactname" type="text" class="L" onchange="" /></div> <div class="required"><label for="company">Company Name:</label><input id="company" name="company" type="text" class="L" /></div> <div class="buttonRow"><input type="submit" name="VERIFY" class="btn red" value="Continue" /></div> </form> And here is my javascript code: Code: function verifyOrder() { if (document.my_form.verified.checked != "true") { alert("Please verify the contents of your order"); document.my_form.verified.focus(); getElementById('document.my_form.verification').className='highlight' return false; } } But this is not working and generates errors in firebug. What am I doing wrong? Thanks!! All, I have a page that has some checkboxes in it. I have the following function for that: Code: function checkbeforesubmit(field) { for (var i = 0; i < field.length; i++){ if(field[i].checked){ // if a field is checked form is submitted alert("You have checkboxes that are selected. Add the photos before you go to the next set of pictures!"); return false; } } return true; // if no fields are checked form not submitted } I then a link to go to the next page and I want to check to see if any checkboxes are selected before I go to the next page. I try and check this by doing this: Code: onClick="checkbeforesubmit(document.photos.elements['picbigid[]'])" It does the check and says that a checkbox is selected but will still go to the next page anyway. How can I stop it from going to the next page? Thanks! Please see my Booking Form here http://www.n-v-m.co.uk/Booking.html The form is very nearly finished but I have no experience with JavaScript at all so I am hoping somebody can tell me how to do the finishing touches. All I require is: 1- On clicking the 'Submit order' button I would like the browser to check to see if the 'Is Vehicle roadworthy with full M.O.T.:' List/Menu is set to 'Yes' and if not it needs to return an alert stating it must be set to 'Yes' to proceed... Somebody kindly helped show me how to do the alert before so this is working, but, the problem at the moment is after clicking 'OK' to close the alert, the form is still submitted. At this point instead of the form being submitted I would just like the browser to return to the form. 2- There is a checkbox on the bottom of the form that states 'I agree with the Terms and Conditions'... To be able to proceed with a booking I need the customer to check the box... On clicking 'Submit order' if the box isn't checked I would like an alert to appear and the form not to be submitted. 3. When both the above criteria have been met and the form is ready to submit... I would like the browser to re-direct to http://www.n-v-m.co.uk/Thankyou.html which is a page I have already created on my server. Thanks for taking your time to read this... If it helps I have posted both my HTML and PHP codes below: Booking.html Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>National Vehicle Movements - Booking Form</title> <style type="text/css"> <!-- body { background-color: #1d255f; margin: 0px; padding: 0px; } #apDiv1 { position:absolute; width:487px; height:706px; z-index:auto; left: 50%; top: 433px; font-family: Arial, Helvetica, sans-serif; font-size: 10px; font-weight: bold; text-align: center; textarea-align: center; background-position: center; margin-left: -244px; } --> </style> <script type='text/javascript'> function isValid() { var box = document.getElementById('Is Vehicle Roadworthy with Full M.O.T.'); if(box.value = 'no') { alert('The vehicle must be roadworthy with full M.O.T'); return false; } } </script> </head> <body> <div align="left"> <div id="apDiv1"> <form id="form1" name="form1" method="post" action="sendform.php" onsubmit='validatethis()'> <table width="400" border="0" align="center"> <tr> <td width="193" align="right">Company:</td> <td width="197" align="left"><input type="text" name="company" id="Company" /></td> </tr> <tr> <td align="right">Name:</td> <td align="left"><input type="text" name="name" id="Name" /></td> </tr> <tr> <td align="right">Phone Number:</td> <td align="left"><input type="text" name="phonenum" id="Phone Number" /></td> </tr> <tr> <td align="right">Email Address:</td> <td align="left"><input type="text" name="email" id="Email" /></td> </tr> <tr> <td align="right">Vehicle Make and Model:</td> <td align="left"><input type="text" name="vmam" id="Vehicle Make and Model" /></td> </tr> <tr> <td align="right">Vehicle Reg./Ref. No.:</td> <td align="left"><input type="text" name="vreg" id="Vehicle Reg." /></td> </tr> <tr> <td align="right">Collection Address including Postcode:</td> <td align="left"><textarea name="colladd" rows="4" id="Collection Address"></textarea></td> </tr> <tr> <td align="right">Collection Contact Name:</td> <td align="left"><input type="text" name="collconname" id="Collection Contact Name" /></td> </tr> <tr> <td align="right">Collection Contact Number:</td> <td align="left"><input type="text" name="collconnum" id="Collection Contact Number" /></td> </tr> <tr> <td align="right">Delivery Address including Postcode:</td> <td align="left"><textarea name="deladd" rows="4" id="Delivery Address"></textarea></td> </tr> <tr> <td align="right">Delivery Contact Name:</td> <td align="left"><input type="text" name="delconname" id="Delivery Contact Name" /></td> </tr> <tr> <td align="right">Delivery Contact Number:</td> <td align="left"><input type="text" name="delconnum" id="Delivery Contact Number" /></td> </tr> <tr> <td align="right">Collection Date/Time:</td> <td align="left"><input type="text" name="collectiondt" id="Collection Date/Time" /></td> </tr> <tr align="center"> <td colspan="2" valign="top"><em>(if possible please give a time window eg. '7th - 9th August' and we will arrange collection for you)</em></td> </tr> <tr> <td align="right">Delivery Date/Time:</td> <td align="left"><input type="text" name="deliverydt" id="Delivery Date/Time" /></td> </tr> <tr align="center"> <td colspan="2" valign="top"><em>(if possible please give a time window eg. '7th - 9th August' and we will arrange delivery for you)</em></td> </tr> <tr> <td align="right">Is Vehicle Taxed:</td> <td align="left"><select name="Taxed" id="Is Vehicle Taxed"> <option>Yes</option> <option selected="selected">No</option> </select></td> </tr> <tr> <td align="right">Is Vehicle roadworthy with full M.O.T.:</td> <td align="left"><select name="mot" id="Is Vehicle Roadworthy with Full M.O.T."> <option>Yes</option> <option selected="selected">No</option> </select></td> </tr> <tr> <td align="right">Billing Address:</td> <td align="left"><textarea name="billadd" rows="3" id="Billing Address"></textarea></td> </tr> <tr align="center"> <td colspan="2" valign="top"><em>(if same as collection or delivery address please enter 'collection' or 'delivery')</em></td> </tr> <tr> <td align="right">Your Ref./Order No. (if any):</td> <td align="left"><input type="text" name="custordnum" id="Customer Ref./Order No." /></td> </tr> <tr> <td align="right">Any additional comments:</td> <td align="left"><textarea name="addcom" rows="3" id="Any additional comments"></textarea></td> </tr> <tr align="center" valign="middle"> <td colspan="2"> <p> <input type="checkbox" name="checkbox" id="checkbox" /> I agree with the <u><a href="Terms.html">Terms and Conditions</a></u></strong></p> <p> </p></td> </tr> <tr align="center"> <td colspan="2"><input type="submit" name="button" id="button" value="Submit order" onclick="isValid()" /> <input type="reset" name="button2" id="button2" value="Reset form" /></td> </tr> </table> </form> </div> </div> <div align="center"><img src="images/Booking_03.jpg" width="680" height="1352" border="0" usemap="#Map" /> <map name="Map" id="Map"> <area shape="rect" coords="36,155,158,173" href="index.html" alt="Home" /> <area shape="rect" coords="29,174,151,189" href="Prices.html" alt="Prices" /> <area shape="rect" coords="475,191,578,206" href="mailto:info@n-v-m.co.uk" alt="Email us" /> </map> </div> </body> </html> sendform.php Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <BODY> <?php $Name = $_POST['name']; //senders name $to = "info@n-v-m.co.uk"; //recipient $subject = "Order from ".$_POST['company']." (".$_POST['name'].")"; //subject $message = $_POST['company']."|".$_POST['name']."|".$_POST['phonenum']."|".$_POST['email']."|".$_POST['vmam']."|".$_POST['vreg']."|".$_POST['colladd']."|".$_POST['collconname']."|".$_POST['collconnum']."|".$_POST['deladd']."|".$_POST['delconname']."|".$_POST['delconnum']."|".$_POST['collectiondt']."|".$_POST['deliverydt']."|".$_POST['Taxed']."|".$_POST['billadd']."|".$_POST['custordnum']."|".$_POST['addcom']; //mail body $from = "NVM Booking Form"; // $headers = "From: ".$from."\r\n"; //optional headerfields mail($to, $subject, $message, $headers); //mail command :) you can add any variable here... I know you have so many, but it is possible... if(mail) echo "Booking confirmed. Thank You!"; else echo "Sorry We Can't Proceed, Please Try After Some Time!"; ?> </BODY> </HTML> I am trying to make validation for a form but the bit I am stuck on now is: Code: <input class="submit" type="submit" value="Submit" id="submit" name="submit" onclick="return validate();" /> Do I have to add 'verify' instead of the 'validate' I mean is this a set thing in JS as I want it to go to the JavaScript code which is validate.js I should add that the form is XHTML and there is also a captcha with it. So I would not know how to add the onsubmit to the beginning of the form. How do I fix the problem that autocomplete does not validate, I have heard before that there is a dirty way to do this but did not want to do this before, but now feel i must as my boss wants the site error free ! does anyone know how I do this ? Is there a y regular expression which we can use in JavaScript to validate URL? Or any other type of validation to validate URL which has http or https?
hi, I would to validate a textbox, and limit it to 3alphabets and 3 numbers. That is after the user have input 3 alphabets, he can only enter 3 numbers and nothing more. Can someone help me out? All, I have the following code which validates a form has at least one checkbox checked before it submits it. However I want to make sure that there aren't more then 25 checked on the page. How can I do this? Code: function validate(field) { for (var i = 0; i < field.length; i++){ if(field[i].checked){ // if a field is checked form is submitted return true; } } alert("You need to have a check box selected to submit the form!"); return false; // if no fields are checked form not submitted } Thanks in advance! My form generates 1 to n records which contains check boxes. Based on some condition if I click a check box it has to check & disable some other check boxes automatically. I did it. But, at the same time if I un-check I have to un-check all the check boxes which were checked. Please let me know. Thanks a lot.
have a simple calculator i made with checkboxes and some Js. the problem is that it does not work in FF. any idea how this can work for IE Safari AND FF Code: function getPrice(amount, boxName){ total = eval() ; checked = document.getElementById(boxName).checked if (checked){ total = parseFloat(form1.Total2.value) + parseFloat(amount); }else{ total = parseFloat(form1.Total2.value) - parseFloat(amount); } total.toFixed(2); form1.Total2.value = total document.getElementById("total").innerHTML = "Total $"+total; } Hi all. I have the following problem that I require a pointer with. I have a php variable named "$seatid" This could contain 1 or many entries. I have a page full of checkboxes named A1-8, B1-8, C1-8 etc to P1-8 I want a way of greying out the checkboxes on the page that relate to the values that are contained in the php variable. So they cannot be clicked. It would also like to change the colour of the cell that the check box is contained in. It is important that the checkboxes or at least the table that contain the checkboxes remain, as it represents the layout of a theatre. Cheers for your help Good evening all, I have a bit of an issue with checkboxes - basically I need to allow only 1 selection and then have a comments box show when a checkbox is checked. I've gotten the comments box to show when the checkbox is checked but I can't seem to workout how to allow only one. I'd really like the user to be able to change their mind and make a different selection but only have 1 be selected at a time (sort of like radio buttons work). I know it would be much easier and probably better to use radio buttons but that isn't an option with this. (The actual HTML is produced using a style sheet in an application that I am interfacing with so all I can do is use the checkbox.) Here is the code I am using to show or hide the comments box. Code: function HideComments() { var a1 = document.getElementById("crmForm_answer1").checked; var a8 = document.getElementById("crmForm_answer8").checked; var a2 = document.getElementById("crmForm_answer2").checked; var a3 = document.getElementById("crmForm_answer3").checked; var a4 = document.getElementById("crmForm_answer4").checked; var a5 = document.getElementById("crmForm_answer5").checked; var a6 = document.getElementById("crmForm_answer6").checked; var a7 = document.getElementById("crmForm_answer7").checked; var a9 = document.getElementById("crmForm_answer9").checked; var a10 = document.getElementById("crmForm_answer10").checked; if(a1==true) { document.getElementById("crmForm_answer1_value").parentNode.parentNode.style.display = 'block'; } else document.getElementById("crmForm_answer1_value").parentNode.parentNode.style.display = 'none'; if(a8==true) { document.getElementById("crmForm_answer8_value").parentNode.parentNode.style.display = 'block'; } else document.getElementById("crmForm_answer8_value").parentNode.parentNode.style.display = 'none'; if(a2==true) { document.getElementById("crmForm_answer2_value").parentNode.parentNode.style.display = 'block'; } else document.getElementById("crmForm_answer2_value").parentNode.parentNode.style.display = 'none'; if(a3==true) { document.getElementById("crmForm_answer3_value").parentNode.parentNode.style.display = 'block'; } else document.getElementById("crmForm_answer3_value").parentNode.parentNode.style.display = 'none'; if(a4==true) { document.getElementById("crmForm_answer4_value").parentNode.parentNode.style.display = 'block'; } else document.getElementById("crmForm_answer4_value").parentNode.parentNode.style.display = 'none'; if(a5==true) { document.getElementById("crmForm_answer5_value").parentNode.parentNode.style.display = 'block'; } else document.getElementById("crmForm_answer5_value").parentNode.parentNode.style.display = 'none'; if(a6==true) { document.getElementById("crmForm_answer6_value").parentNode.parentNode.style.display = 'block'; } else document.getElementById("crmForm_answer6_value").parentNode.parentNode.style.display = 'none'; if(a7==true) { document.getElementById("crmForm_answer7_value").parentNode.parentNode.style.display = 'block'; } else document.getElementById("crmForm_answer7_value").parentNode.parentNode.style.display = 'none'; if(a9==true) { document.getElementById("crmForm_answer9_value").parentNode.parentNode.style.display = 'block'; } else document.getElementById("crmForm_answer9_value").parentNode.parentNode.style.display = 'none'; if(a10==true) { document.getElementById("crmForm_answer10_value").parentNode.parentNode.style.display = 'block'; } else document.getElementById("crmForm_answer10_value").parentNode.parentNode.style.display = 'none'; } Thanks in Advance Sam Hi, i have a problem to validate time range in javascript. i've search in the website and found some example. below is the my coding Code: function timeCheck(){ branchCode = <%=sessionUser.getBranchCode()%>; var d = new Date(); var curr_hour = d.getHours(); var curr_min = d.getMinutes(); if (curr_min < 10){ curr_min = "0" + curr_min } var currtime = curr_hour + ":" + curr_min; if(branchCode >= 1 && branchCode <= 5){ st = "7:30"; et = "9:00"; } else if(branchCode >= 6 && branchCode <= 10){ st = "9:01"; et = "10:30"; } else if(branchCode >= 11 && branchCode <= 15){ st = "10:31"; et = "12:00"; } else if(branchCode >= 16 && branchCode <= 20){ st = "12:01"; et = "13:30"; } else if(branchCode >= 21 && branchCode <= 26){ st = "13:31"; et = "15:00"; } else if(branchCode >= 27 && branchCode <= 31){ st = "15:01"; et = "16:30"; } else if(branchCode >= 32 && branchCode <= 71){ st = "16:31"; et = "18:00"; } else { st = "6:30"; et = "19:00"; } if(validate_time(currtime,st,et)){ alert("Cannot access this page"); location.href='<%=request.getContextPath()%>/security/welcome.do'; } } function validate_time(currtime,st,et ){ currtime = currtime.split(/:/); st = st.split(/:/); et = et.split(/:/); return ( currtime[0] < st[0] || currtime[0] > et[0] || (currtime[0] == st[0] && currtime[1] < st[1]) || (currtime[0] == et[0] && currtime[1] > et[1]) ); //return TRUE if time not in range } i want to control user's access to the page. they can only access within the range given. example: current time = 10:14 st = 9:01 et = 10:30 When I test, the currtime[0] < st[0] return true. I don't understand why the statement return true. can someone help me? Thanks in advance. How do I validate that one of the below buttons is selected? Code: <input type="radio" name="car" class="radio" value="YES" >Yes <input type="radio" name="car" class="radio" value="NO"> No hello i am trying to do a validation form but i ended up with one that only works for chrome, not on IE not on Firefox! don't know why!!! and another problem it looks like that the return false doesn't even work, it proceeds to the next page anyway [HTML]function validate_required(field,alerttxt) { with (field) { if (value==null||value=="-1") { alert(alerttxt); return false; } else { return true; } } } /*function alertt(thisform) {alert(thisform);}*/ function validate_form(thisform) { //alert('hi'); with (thisform) { if (validate_required(i_am_a,"i_am_a must be filled out!")=="-1") {i_am_a.focus(); return false;} } [/HTML] [HTML]<form method="post" action="index.php?page=step2" onsubmit="return validate_form(i_am_a.options[i_am_a.selectedIndex].value);"> <table class="text"> <tr> <td class="text">أنا</td> <td> <select name="i_am_a" id="i_am_a"> <!--onchange="validate_form(i_am_a.options[i_am_a.selectedIndex].value);">--> <option selected value="-1">الرجاء التحديد</option> <option value="MSW">رجل يبحث عن إمرأة</option> <option value="WSM">إمرأة تبحث عن رجل</option> </select> </td> </tr><tr class="submit"> <td> </td> <td> <input type="submit" value="إنضمم الآن مجانا" /> </td> </tr> </table> </form>[/HTML] Good Afternoon All, I am slowly learning how to validate forms and the next topic I'm learning is the phone feature! My code isn't working and not sure why! I read other opinions and tried to follow some templates but again.. Nothing is working out for me.. Here is the code function validatePhone(fld) { var stripped = document.validatePhone.phoneNumber(/[\(\)\.\-\ ]/g, ''); if (document.validatePhone.phoneNmbr == "") { alert("Do not leave this field blank"); } else if (isNaN(parseInt(stripped))) { alert("Only enter numerical digits only"); } else if (!(stripped.length == 10)) { alert("No More or Less than 10 Digits"); } return error; } <body> <form name="validatePhone" action="" method="get"><br /> <br /> <input type="text" name="phoneNumber" value="" onClick="return validatePhone(fld)"> <br /> <br /> <input type="button" name="button" value="Validate Phone Number" > </form> </body> </html> If you have any suggestions or can provide links of how I can 1-Provide an alert if the field is blank 2-Provide an alert if non numerical digits are entered 3-Provide an alert if more than 10 digits are entered I think I am on the right track but need more of a push.. I'm not seeking a solution, just information to get me on that right track as I am extremely confused. Also.. I feel like I should be using a isDigit function? Hello guys, this is my first post here, im a newbie in javascript and i need to limit a textbox to only be 1 or 0, I dont want to use a checkbox because i would like the users to really be typing. heres what i got: Code: <input name="test" type="text" onchange="validaten(this.value)" size="15" /> <script type="text/javascript"> function validaten(test) { if (test != 0); alert("Only 1 and 0 are allowed"); } </script> Can you please help me? |