JavaScript - Radio And Checkbox (nested) Validation
Hello,
After pulling out all my hairs, I am seeking some help with a JS validation script which would be for a case where we have multiple radio buttons which required a response from user and as a additional case if certain radio option is selected user should select one or more options listed as check boxes under that specific radio button. I have attached an image showing sample scenario with this post. If someone has an Idea how to to do please sail me thru. Similar TutorialsHey all. I have a simple validation I need to do. I need to just make sure that a Checkbox is checked, and that a Text field has content. Sounds simple but I cannot find any thing that has a check and a text field. Here what I have. Can I modify this script to do this? A Checkbox MUST be checked and Text field MUST be filled out. This currently does the text field fine, but no Checkbox obviously. How can I add a checkbox validation to this? Thats it. Any help is appreciated. Code: <script type="text/javascript"> var textFields = ["digsig"]; function validateForm( ) { var oops = ""; // must initialize this! var form = document.sig; for ( var t = 0; t < textFields.length; ++t ) { var field = form[textFields[t]]; var value = field.value.replace(/^\s+/,"").replace(/\s+$/,""); // trim the input if ( value.length < 1 ) { oops += "You MUST enter your Digital Signature"; } } if ( oops != "" ) { alert("ERROR:" + oops); return false; } } } </script> hi can someone help me on my code on javascript sory im a newbie can you check this and help me what i need to do to add all the radio botton and check box. i already finish the add formula on the checkbox but i do not know how to add the two selected radio buttons to my checkbox buttons help please... for example: O selected is 80 O 60 O 60 O selected is 15 O 15 O 25 chkbox 22 chkbox 30 chkbox 8 Code: function Compute(form) { if(form.radio1[0].checked) form.text1.value=form.radio1[0].value; <---- the value of this is 80 else if(form.radio1[1].checked) form.text1.value=form.radio1[1].value; <---- 60 else if(form.radio1[2].checked) form.text1.value=form.radio1[2].value; <---- 60 else if(form.radio1[0].checked) form.text1.value=form.radio1[0].value; <---- 15 else if(form.radio2[1].checked) form.text1.value=form.radio2[1].value; <---- 15 else if(form.radio2[2].checked) form.text1.value=form.radio2[2].value; <---- 25 var a=0; if(form.chk1.checked) <----22 a = a + eval(form.chk1.value); if(form.chk2.checked) <----30 a = a + eval(form.chk2.value); if(form.chk3.checked) <----8 a = a + eval(form.chk3.value); if(form.chk1.checked && form.chk2.checked) a = eval(form.chk1.value) + eval(form.chk2.value); if(form.chk1.checked && form.chk3.checked) a = eval(form.chk1.value) + eval(form.chk3.value); if(form.chk2.checked && form.chk1.checked) a = eval(form.chk2.value) + eval(form.chk1.value); if(form.chk2.checked && form.chk3.checked) a = eval(form.chk2.value) + eval(form.chk3.value); if(form.chk3.checked && form.chk1.checked) a = eval(form.chk3.value) + eval(form.chk1.value); if(form.chk3.checked && form.chk2.checked) a = eval(form.chk3.value) + eval(form.chk2.value); if(form.chk1.checked && form.chk2.checked && form.chk3.checked) a = eval(form.chk1.value) + eval(form.chk2.value) + eval(form.chk3.value); form.text1.value=a; } I have a page where a user can select (via check boxes) several categories. Each category is related to a set of possible options (radio buttons) that have numeric values. When one of the options (radio button) is selected, the amount will appear in a text box (input type="text"). The numeric value in the text box will update depending on what category options are selected. However, when the checkbox is deselected, the radio boxes in the <div> are not displayed and I need to remove (reset) the radio button values from the value seen in the text box. Here are some snippets to hopefully expound on what I would like to do. Code: <script type="text/javascript"> var amountNotice = 0; function notice(options) { amountNotice = parseInt(options); calculateTotal(); } function calculateTotal() { totalAmount = amountNotice; document.getElementById("total").value = totalAmount.toFixed(2); } function toggle(chkbox, group, associatedValues) { var visSetting; if (chkbox.checked == true) document.getElementById(group).style.display = "inline"; else { document.getElementById(group).style.display = "none"; uncheckRadio(associatedValues); } document.getElementById(group).style.display = visSetting; } function uncheckRadio(associatedValues) { for(var i = 0; i < document.getElementById(associatedValues).length; i++) { if (associatedValues[i].checked == true) associatedValues[i].checked == false; } calculateTotal(); } </script> <style type="text/css"> #groupNotice {display: none} </script> . . <input type="button" onClick="calculateTotal()" value="Calculate"><br> <div id="groupNotice"> <b>Required Notice</b>: <input type="radio" name="Note" onClick="notice(this.value)" value="0"> None <input type="radio" name="Note" onClick="notice(this.value)" value="2"> Prior Day ($2) <input type="radio" name="Note" onClick="notice(this.value)" value="2"> Prior Call ($2)<br> </div> <form name="CostEstimate" method="post" action="calculator.php"> <input type="checkbox" onclick="toggle(this, 'groupNotice', 'Note'); display('groupNotice','inline')" name="Notice" value=""> Notice </form> Everything works except for my uncheckRadio function - not sure if I am identifying the elements correctly, or if I need a totally new approach. My thinking is that the function must be accessed by the checkbox onClick call. Previously I had tried calling uncheckRadio from the notice function before I recognized is was not an appropriate location. Any assistance is greatly appreciated. - c Hey guys, I am having a bit of an issue here. I have a form which has 3 checkboxes in it: (sorry, ignore the asp) Code: <input name="certs" id="certs" type="checkbox" <% If certs="on" Then Response.Write("checked=""checked""") %> /> <input name="nocerts" id="nocerts" type="checkbox" <% If nocerts="on" Then Response.Write("checked=""checked""") %> /> <input name="certsna" id="certsna" type="checkbox" <% If certsna="on" Then Response.Write("checked=""checked""") %> /> Anyways, I want to enforce the following: - Only one checkbox can be checked from these 3, no more - At least one checkbox must be checked before submission I have found a couple small scripts to validate that at least one is pressed, but I do not know how to make sure no more than one is pressed, and how to combine scripts is beyond me. Can anyone offer any assistance? Is this difficult to do? Hi All I am not a genius when it comes to javascript so if anyone could help, I would really be grateful. scenario: I am creating a custom product (75g) which will be made up of 3 others products (25g + 25g + 25g). The 3 options will be made up of a combination of smaller products each with their own options (25g, 50g, 75g) which will allow the customer to have one of each or fill up all 3 with just one type. Here is what I have in code already: Code: <div class="wrapperAttribsOptions"> <h4 class="optionName back">Organic Sour Worms</h4> <div class="back"> <input name="id[14][48]" value="48" id="attrib-14-48" type="checkbox"><label class="attribsCheckbox" for="attrib-14-48">25g</label><br> <input name="id[14][49]" value="49" id="attrib-14-49" type="checkbox"><label class="attribsCheckbox" for="attrib-14-49">50g</label><br> <input name="id[14][50]" value="50" id="attrib-14-50" type="checkbox"><label class="attribsCheckbox" for="attrib-14-50">75g</label><br> </div> <br class="clearBoth"> </div> <br class="clearBoth"> <div class="wrapperAttribsOptions"> <h4 class="optionName back">Organic Sugar Bears</h4> <div class="back"> <input name="id[15][51]" value="51" id="attrib-15-51" type="checkbox"><label class="attribsCheckbox" for="attrib-15-51">25g</label><br> <input name="id[15][52]" value="52" id="attrib-15-52" type="checkbox"><label class="attribsCheckbox" for="attrib-15-52">50g</label><br> <input name="id[15][53]" value="53" id="attrib-15-53" type="checkbox"><label class="attribsCheckbox" for="attrib-15-53">75g</label><br> </div> <br class="clearBoth"> </div> <br class="clearBoth"> <div class="wrapperAttribsOptions"> <h4 class="optionName back">Organic Fruit Cocktail</h4> <div class="back"> <input name="id[16][54]" value="54" id="attrib-16-54" type="checkbox"><label class="attribsCheckbox" for="attrib-16-54">25g</label><br> <input name="id[16][55]" value="55" id="attrib-16-55" type="checkbox"><label class="attribsCheckbox" for="attrib-16-55">50g</label><br> <input name="id[16][59]" value="59" id="attrib-16-59" type="checkbox"><label class="attribsCheckbox" for="attrib-16-59">75g</label><br> </div> <br class="clearBoth"> </div> <br class="clearBoth"> <div class="wrapperAttribsOptions"> <h4 class="optionName back">Organic Jelly Bears</h4> <div class="back"> <input name="id[17][57]" value="57" id="attrib-17-57" type="checkbox"><label class="attribsCheckbox" for="attrib-17-57">25g</label><br> <input name="id[17][58]" value="58" id="attrib-17-58" type="checkbox"><label class="attribsCheckbox" for="attrib-17-58">50g</label><br> <input name="id[17][60]" value="60" id="attrib-17-60" type="checkbox"><label class="attribsCheckbox" for="attrib-17-60">75g</label><br> </div> <br class="clearBoth"> </div> What I need to do is to some how ensure that the product is filled with 75g worth of the other products. Another option may to not use the 'grams' but rather use the 3 compartments that will be filled so 25g = 1, 50g = 2, 75g = 3 etc. Note: Name, Values, Ids are made dynamically by the cart, and I cannot change those as they are used for adding to cart and updating account info etc. PLEASE PLEASE PLEASE if anyone can help, I would really appreciate it. ----------------------------- Jay confused. my validation of the clicking on a checkbox doesn't seem to send the value with the form. Should I be adding value='whatever' in the xhtml? Code: <form method="post" id='myForm' name='myForm' onsubmit="return checkform(this)" action="/cgi-bin/script/520/9/98"> <script type='text/javascript'> //<![CDATA[ function checkform(form) { //validate the terms checkbox if (!document.myForm.acceptance.checked) { // ! means "not" document.getElementById("trmserr").innerHTML = "You must accept the terms and conditions"; document.getElementById("myForm").acceptance.value = ""; // clear the field setTimeout("document.getElementById('myForm').acceptance.focus()", 25); // refocus on it return false; } else { document.getElementById("trmserr").innerHTML = ""; } return true; } <span id="trmserr" class='formErrorWarning'></span> <p> <a class='tooltip' href='#'> <span class='compulsory'>*</span> <span class='the_tip'>This is required because, by proceeding, you are accepting these terms and conditions for this purchase. They will be emailed to you along with your order confirmation.</span></a> <input type="checkbox" id='acceptance' name="acceptance" /> I have read and I accept the terms and conditions.</p> It works if JS is disabled and it works only sometimes when it is enabled. I have a form, on which I have multiple checkboxes and text fields. Now I want that the form can't submit untill at least 1 checkbox is selected or a text field is filled. But even with the javascript validation I already have the form still submits. Any help on this one? Here is the whole page on which the checkboxes, text fields and javascript validation a PHP Code: <script type="text/javascript" language="javascript"> function checkCheckBoxes() { if (document.form2.nbs_vmb[].checked == false) { alert ('Select at least checkbox to make a selection!'); return false; } else { return true; } </script> <div id="left2"> <div id="left_02"> <div id="toppage"> <h3><?php echo $tcm_label[59]; ?></h3> </div> <div style="margin:0px 1px 0px 1px"> <form id="form_ins_contact" onsubmit="return checkCheckBoxes();" name="form2" action="test.php" method="POST" > <table width="680" height="350" border="0" align="center" cellpadding="0" cellspacing="2"> <tr> <td width="160" align="right"><strong><?php echo $tcm_label[36]; ?></strong></td> <td class="td_no_border"><input name="nbs_vmb[]" type="checkbox" value="nbs_lid_vmb" /></td> <td class="td_no_border2"></td> <td class="td_no_border2"></td> </tr> <tr> <td width="160" align="right"><strong><?php echo $tcm_label[37]; ?></strong></td> <td class="td_no_border"><input name="nbs_vmb[]" type="checkbox" value="nbs_selfburns" /></td> <td align="right"><strong><?php echo $tcm_label[29]; ?></strong></td> <td class="td_no_border"><input name="nbs_zip" type="text" id="nbs_zip" maxlength="6" size="6" /></td> </tr> <tr> <td width="160" align="right"><strong><?php echo $tcm_label[40]; ?></strong></td> <td class="td_no_border"><input name="nbs_vmb[]" type="checkbox" value="nbs_profrelatie" /></td> <td align="right"><strong><?php echo $tcm_label[60]; ?></strong></td> <td class="td_no_border"><input name="nbs_contact_year" type="text" id="nbs_contact_year" maxlength="4" size="4" /></td> </tr> <tr> <td width="160" align="right"><strong><?php echo $tcm_label[42]; ?></strong></td> <td class="td_no_border"><input name="nbs_vmb[]" type="checkbox" value="nbs_revalinet" /></td> <td align="right"><strong><?php echo $tcm_label[38]; ?></strong></td> <td class="td_no_border" width="194"><input name="nbs_year" type="text" id="nbs_year" maxlength="4" size="4" /></td> </tr> <tr> <td align="right"><strong><?php echo $tcm_label[44]; ?></strong></td> <td class="td_no_border"><input name="nbs_vmb[]" type="checkbox" value="nbs_juridischehulp" /></td> <td align="right"><strong><?php echo $tcm_label[41]; ?></strong></td> <td class="td_no_border" width="194"><input name="nbs_vmb[]" type="checkbox" value="nbs_psychonet" /></td> </tr> <tr> <td align="right"><strong><?php echo $tcm_label[45]; ?></strong></td> <td class="td_no_border"><input name="nbs_vmb[]" type="checkbox" value="nbs_nomail" /></td> <td align="right"><strong><?php echo $tcm_label[43]; ?></strong></td> <td class="td_no_border"><input name="nbs_vmb[]" type="checkbox" value="nbs_reintegranet" /></td> </tr> <tr> <td align="right" class="td_no_border2"> </td> <td class="td_no_border2"> </td> <td></td> <td class="td_no_border2"><img src="../images/intra icon.png" width="96" height="96" /></td> </tr> </table> <table width="281" border="0" align="center" cellpadding="0" cellspacing="2"> <tr> <td align="center" class="td_no_border2" nowrap="nowrap"> <input type="submit" name="submit" class="buttons" value="Export Selecties" /> </td> </tr> </table> </form> </div> </div> </div> Thanks in advanced. I have a simple html form with 2 text fields and submit button 1 user name 2 pwd/token and 1 checkbox 'First time user' if 'first time user' is selected then the 'Submit' button to be enabled only if the customer puts exactly 6 digits on pwd/token. if it's unchecked then the submit button to be enabled only if the customer enters 10 digits(pin_token code) please send me code will be very thankful for your help First of all Thank you for looking at my issues. Just so you know, I am not a coder I have a new set of problems I'm hoping someone can help me with. Please read all three problems listed below as they are all intertwined. Thank you for any assistance you have with these issues. First, here is the url to my test form http://www.rocpinions.com/test-main-form.html Next, Here is the code I am using. The code is set up on dog cat other and none. The test check 1 etc are all individual check box groups Code: <script type="text/javascript"> function checkI() { var other=0; var checkL = document.getElementsByName('form[PetsInHouse][]'); for (var i=0;i<checkL.length-1;i++){ if(document.getElementById('PetsInHouse3').checked){ document.getElementById('PetsInHouse'+i).disabled = true; document.getElementById('PetsInHouse'+i).checked = false; } else { document.getElementById('PetsInHouse'+i).disabled = false; } if(document.getElementById('PetsInHouse'+i).checked){ other++ } } document.getElementById('PetsInHouse3').disabled=other>0?true:false; } </script> And here is the call I am using onclick="checkI();" Problem 1 This code works fine as is is set up and does what it should. The problem is i am also using this on longer sets of check boxes and I would like to instead of disabling I would like to have it set up so if someone clicks dog cat and other then if they choose the check box "None" it would empty all other check boxes and check the check box "None" and visa versa if none was checked and they checked dog, it would empty the None check. Problem 2 I am using Joomla cms and a form constructor called RS Form Pro. It stores the data submitted in the form to a data base. As it is now, all the info in the check box group is submitted to ONE column. I need to submit it to individual columns for each choice. I can accomplish this by using individual check box groups for EACH item. This will put it in separate columns in the data base but I still need to have it set up so if someone clicks dog cat and other then if they choose the check box "None" it would empty all other check boxes and check the check box "None" and visa versa if none was checked and they checked dog, it would empty the None check. Problem 3 How it submits data to the data base Right now, it submits the data from the check boxes by the name of the check box. What I would like to have is a 1 if it IS checked and a 0 if IS NOT checked. Again, Thank you for any assistance DeZiner I am trying to use some JavaScript code that I found by searching the web, my goal is to have a form with a "required" checkbox to force my users to acknowledge they have read my "Terms and Conditions" section. The code that I found ALMOST works properly - it does pop-up the "Alert" window when the checkbox is blank and the submit button is clicked... however, if the user closes the Alert window in order to click the checkbox in compliance, the "submit.form" command is executed before they have a chance. In other words, there is no "pause" in the execution of the script to allow the user to make the correction by clicking the checkbox. Here is the code: Code: <script LANGUAGE="JavaScript"> <!-- function ValidateForm(form){ ErrorText= ""; if ( form.terms.checked == false ) { alert ( "Please check the Terms & Conditions box." ); return false; } if (ErrorText= "") { form.submit() }} --> </script> Here is the HTML for the checkbox: Code: <input name="terms" type="checkbox" value="Yes" /> Here is the HTML for the submit button that calls the function: Code: <input type="submit" value="Continue" onclick="ValidateForm(this.form)" /> I've searched for other examples of code to accomplish this objective, but I'm hoping for a quicker solution by coming to the experts who can see the flaw in this JavaScript. Thanks for any help, Rob Hi everyone. I'm getting into javascript coding and i'm stumped with some problem about radio buttons. What I would like is to have a general function where I can pass in any group of radio buttons and have it return the textual value of the radio button selected. First, here is my code so far. Code: function Get_Radio_Selection(options) { var choice = ""; for (var index = 0; index <= options.length; index++) if (options[index].checked == true) choice = options[index].value; return choice; } Now here's a sample form: Code: <form name="form1"> <input type="radio" name="food" value="Banana">Banana <input type="radio" name="food" value="Mango">Mango <input type="radio" name="food" value="Orange">Orange <input type="radio" name="food" value="Oatmeal">Oatmeal <input type="button" name="blah" value="Get Selection" onclick="Get_Radio_Selection(document.form1.food);"> </form> My question is, when i run this function and pass it in the group of radio buttons by means of the onclick event handler, firefox 3.6.22 reports in the error console on line 22 that "options[index] is undefined". It seems that if i use the variable "index" more than one time it reports this error but if I take out the assignment to variable "choice" that it works just fine. I rewrote the function using a separate variable and this time it works perfectly: Code: function Get_Radio_Selection(options) { var choice = ""; var index; for (var i = 0; i < options.length; i++) { if (options[i].checked == true) { index = i; choice = options[index].value; } } return choice; } Notice the indexing variables in the "if" statement and the assignment to "choice" are different. Does anyone have any suggestions on why this happens? Thanks. how would i check to see if my radio button is not checked. I know in javascript the term "checked" works. Is there a way to us unchecked? here is what i am trying to figure out. Code: with (thisform) { if(document.getElementById('m21').unchecked) { window.alert('Please Verify Your Age') m21.focus(); return false;} } i'm running a validation script to check if my radio buttons are selected, but i can't seem to get it to read the value of the field. heres my form Code: <form name="cases" action="cases_process.php" method="post" onsubmit="return validate(this)"> <input name="uscan" id="uscan" value="n" checked="checked" type="hidden" /> <input type="radio" name="uscan" id="uscan" value="us" class="radial" tabindex="1" /><label>United States</label> <input type="radio" name="uscan" id="uscan" value="canada" class="radial" tabindex="2" style="margin-left:30px;" /><label>Canada</label> <input type="radio" name="uscan" id="uscan" value="other" class="radial" tabindex="3" style="margin-left:30px;" /><label>Other</label> <div style="float:left;margin:-23px 0 0 370px;" id="cancelcon_uscan"></div> </div> <table class="category"> <tr><td><label>Case Name:</label></td><td><input type="text" name="casename" id="casename" class="field" tabindex="6" /></td> <td><div id="cancelcon_casename"></div></td></tr> </table> </form> i have a hidden checked field with a value of n, so there is a value of "n" for "uscan" if no radio is selected. i then run this code on submit: Code: function validate(form) { var uscan = form.uscan.value; var casename = form.casename.value; var reWhiteSpace = new RegExp(/^\s+$/); if(uscan == "n") { modinputbad('uscan'); var a = "1"; }else { modinputgood('uscan'); var a = "0"; } if(casename == "" || reWhiteSpace.test(casename) == true) { modinputbad('casename'); var b = "1"; }else { modinputgood('casename'); var b = "0"; } function modinputbad(id) { $(id).style.border = '1px solid #b63939'; $(id).style.background = '#ffdfdf'; $('cancelcon_'+id).innerHTML = '<img style="float:left;" src="static/images/cancel_16.png"/>'; } function modinputgood(id) { $(id).style.border = '1px solid #D9D9D9'; $(id).style.background = '#F2F4F3'; $('cancelcon_'+id).innerHTML = ''; } var added = a+b+c+d+e+f; var dowork = added.indexOf('1'); if(dowork == '-1')return true; else return false; } everything works up until the if(uscan == "n") so idk why it cant find what the value of the field is, because ive tested it and it seems to know even know what the value is. anything im doing wrong? Wondering how come this doesn't work any ideas? its validating that the radio buttons have been selected. Code: if ( ( form.q1[0].checked == false ) && ( form.q2[1].checked == false) && ( form.q3[2].checked == false )) { alert ( "Please Choose a " ); return false; } Hi hope someone here can help me with a problem i'm stuck on. Basically I have 3 radio buttons and one of them has to be selected otherwise display a error message but I cant figure it out. Here is my failed attempt: Code: <html> <head> <link rel="stylesheet" type="text/css" href="css/style.css" /> <script type="text/javascript"> function validateForm() { var x=document.forms["form1"]["name"].value; var y=document.form1.difficulty.value; if (x==null || x=="") { alert("First name must be filled out"); return false; } if (y==false) { alert(y); return false; } } </script> </head> <body> <div id="horizon"> <div id="content"> <img src="images/logo.jpg" width="649" height="410"></div> <div id="content2"><form name ="form1" method ="post" action ="game.php" onSubmit="return validateForm()" > Name: <input type ='text' name='name' /> <br /> <Input type = 'Radio' Name ='difficulty' value= '1' />Easy <Input type = 'Radio' Name ='difficulty' value= '2' />Medium <Input type = 'Radio' Name ='difficulty' value= '3' />Hard <br /><Input type = "Submit" Name = "Submit" VALUE = "Submit"> </form></div></div> </body> </html> Thanks in advance Hi, I am using a script called osDate and I am trying to modify the sign up form to suit my setup. So far I have the below, but I would like to check a set ofradio buttons, but not sure, how to add it into the current code. var alphanumeric_chars = "0123456789.+-_#,/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ()_"; var alphanum_chars = "0123456789_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; var text_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz /'"; var full_chars = "0123456789.+-_#,/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz() _$+=;:?'"; <script type="text/javascript"> /* <![CDATA[ */ function validateme(form) { var tos_ok = form.accept_tos.checked; ErrorCount=0; ErrorMsg = new Array(); /* log details */ CheckFieldString("noblank",form.username,"Please enter the username."); CheckFieldString("alphanum",form.username,"Only letters, numbers and underscores '_' are allowed in the username."); CheckFieldString("noblank",form.email,"Email must be specified."); CheckFieldString("email",form.email,"Email address is not valid."); CheckFieldString("noblank",form.firstname,"First Name must be specified."); CheckFieldString("text",form.firstname,"Only letters are allowed in First Name."); CheckFieldString("noblank",form.lastname,"Last Name must be specified."); CheckFieldString("text",form.lastname,"Only letters are allowed in Last Name."); CheckFieldString("noblank",form.address1,"Last Name must be specified."); CheckFieldString("full",form.address1,"Only letters, numbers and underscores '_' are allowed in the password."); CheckFieldString("full",form.address2,"Only letters, numbers and underscores '_' are allowed in the password."); CheckFieldString("noblank",form.city,"Last Name must be specified."); CheckFieldString("text",form.city,"Only letters are allowed in Last Name."); if(form.username.value.length >= 5 && form.username.value.length <= 20){ if ( !isNaN(form.username.value.charAt(0)) ){ ErrorCount++; ErrorMsg[ErrorCount] = "Username must start with a letter." ; } }else{ ErrorCount++; ErrorMsg[ErrorCount] = "Number of characters in username should be between the specified range." ; } if (tos_ok != true) { ErrorCount++; ErrorMsg[ErrorCount]="Please read and accept the Terms of Service before registering"; } /* concat all error messages into one string */ result=""; if( ErrorCount > 0) { result = "---- Following errors occured -----"+ String.fromCharCode(13)+ String.fromCharCode(10); for( c in ErrorMsg) result += ErrorMsg[c]+ String.fromCharCode(13)+ String.fromCharCode(10)+ String.fromCharCode(10); alert(result); return false; } return true; } /* ]]> */ </script> I wrote a function to to validate some elements in my form and for some reason I can't seem to figure out why my radio validation is not working. There are about 3 to 4 radio buttons. all with the same name, but i need to make sure that at least one out of this group is selected. Below is my code. Any help would be very useful. Thanks! JS: Code: <script type="text/javascript"> function validate_required(field,alerttxt,select) { with (field) { if (value==null||value=="") { alert(alerttxt);return false; } else { return true; } } } function validate_form(thisform) { with (thisform) { if (document.getElementsByName('sleeper').checked==false) { window.alert('Please select a sleeper') return false;} } } //last </script> Form: Code: <form name="week_picks" method="post" action="confirm.php" onsubmit="return validate_form(this)"> <input name="sleeper" type="radio" value="<?=$sleeper;?>" /> <input name="sleeper" type="radio" value="<?=$sleeper;?>" /> <input name="sleeper" type="radio" value="<?=$sleeper;?>" /> etc... </form> Hi, i'm new here and I need help. I need a script that can alert in 2 ways for multiple radio button groups of "yes" and "no." I got the first question to alert the way I need (with alert #1 for yes and alert#2 for no.) However, starting from the 2nd question it alerts #1 for both yes and no. This is the script I'm working with: Code: <script type="text/javascript"> function valbutton(form) { myOption = -1; for (i=form.buttonset1.length-1; i > 0; i--) { if (form.buttonset1[i].checked) { myOption = i; i = -1; } } if (myOption == -1) { alert("Please select Yes or No"); return false; } if (myOption == 1) { alert("Yes, it works!"); return false; } if (myOption == 2) { alert("No, it won't work."); return false; } } </script> The following are the 1st two sets of radio buttons: Code: <form name="myform" action="formstest.html"> <tr> <td> <input type="reset" value="Click to Reset"> <br><input type="radio" name="buttonset1" value="1" rel="none" id="r1" /><label for="r1">Click to Start Over</label><br /></td> </tr> <tr><td class="question">Question #1</td> <td><input type="radio" name="buttonset1" value="2" rel="flat" id="r2" /> <label for="r2">Yes</label><br /> <input type="radio" name="buttonset1" value="3" rel="none" id="r3" /> <label for="r3">No</label><br /> </td> </tr> <tr rel="flat"> <td class="question"><label for="flat"><span class="accessibility">If metal:</span>Question #2</label></td> <td><input type="radio" name="buttonset2" value="4" rel="uneven" id="r4" /> <label for="r4">Yes</label><br /> <input type="radio" name="buttonset2" value="5" rel="none" id="r5" /> <label for="r5">No</label><br /> </td> </tr> Is it possible to switch out the alerts for yes and no for next 4 questions? And finally, the following is the lengthy, thorough version of my question if it clarifies what I'm trying to do. I would really appreciate someone to point me the right direction. I've tried all kinds of variation to the script and I just can't seem to make it work. Thanks in advance! (Lengthy Version) I also need questions to appear (or not show) below as select radio buttons are clicked. I have 6 groups of yes and no radio buttons. I would like the first two groups to have "alert 1" when yes is clicked (and "alert 2" for no.) I would like the rest to show "alert 2" when yes is clicked (and "alert 1" for no.) (I also have all the questions hidden below question 1. Each subsequent questions appear upon clicking yes for questions 1&2, and no for the rest. I would like to keep this intact - I put that js code I downloaded at the end of this post.) Here's what I have so far... I got most of it working except after the first question, "alert 1" appears for all the clicks submitted. I've been at it for a few weeks and I can't seem to figure it out. Thanks in advance! Code: <html> <head> <title>Form Test</title> <script type="text/javascript"> function valbutton(form) { myOption = -1; for (i=form.buttonset1.length-1; i > 0; i--) { if (form.buttonset1[i].checked) { myOption = i; i = -1; } } if (myOption == -1) { alert("Please select Yes or No"); return false; } if (myOption == 1) { alert("Yes, it works!"); return false; } if (myOption == 2) { alert("No, it won't work."); return false; } } </script> </head> <body> <form name="myform" action="formstest.html"> <tr> <td> <input type="reset" value="Click to Reset"> <br><input type="radio" name="buttonset1" value="1" rel="none" id="r1" /><label for="r1">Click to Start Over</label><br /></td> </tr> <tr><td class="question">Question #1</td> <td><input type="radio" name="buttonset1" value="2" rel="flat" id="r2" /> <label for="r2">Yes</label><br /> <input type="radio" name="buttonset1" value="3" rel="none" id="r3" /> <label for="r3">No</label><br /> </td> </tr> <tr rel="flat"> <td class="question"><label for="flat"><span class="accessibility">If metal:</span>Question #2</label></td> <td><input type="radio" name="buttonset2" value="4" rel="uneven" id="r4" /> <label for="r4">Yes</label><br /> <input type="radio" name="buttonset2" value="5" rel="none" id="r5" /> <label for="r5">No</label><br /> </td> </tr> <tr rel="uneven"> <td class="question"><label for="uneven"><span class="accessibility">If flat:</span> Question #3</label></td> <td><input type="radio" name="buttonset3" value="6" rel="none" id="r6" /> <label for="r6">Yes</label><br /> <input type="radio" name="buttonset3" value="7" rel="ridges" id="r7" /> <label for="r7">No</label><br /> </td> </tr> <tr rel="ridges"> <td class="question"><label for="ridges"><span class="accessibility">If uneven:</span> Question #4</label></td> <td><input type="radio" name="buttonset4" value="8" rel="none" id="r8" /> <label for="r8">Yes</label><br /> <input type="radio" name="buttonset4" value="9" rel="holes" id="r9" /> <label for="r9">No</label><br /> </td> </tr> <tr rel="holes"> <td class="question"><label for="holes"><span class="accessibility">If ridges:</span> Question #5</label></td> <td><input type="radio" name="buttonset5" value="10" rel="none" id="r10" /> <label for="r10">Yes</label><br /> <input type="radio" name="buttonset5" value="11" rel="curved" id="r11" /> <label for="r11">No</label><br /> </td> </tr> <tr rel="curved"> <td class="question"><label for="curved"><span class="accessibility">If holes:</span>Question #6 </label></td> <td><input type="radio" name="buttonset6" value="12" rel="none" id="r12" /> <label for="r12">Yes</label><br /> <input type="radio" name="buttonset6" value="13" rel="answer" id="r13" /> <label for="r13">No</label><br /> </td> </tr> <tr rel="answer"> <td></td> <td class="question"><label for="answer"><span class="accessibility">If not curved:</span><strong> Yes, correct answer!</strong></label></td> </tr> <tr> <td colspan="2"><input type="submit" name="submitit" onclick="valbutton(myform);return false;" value="Submit" /></td> </tr> </tbody> </table> </form> </body> </html> The following is the JS found to make corresponding questions appear as each relevant radio button answer is clicked: Code: /*****************************************/ /** Usable Forms 2.0, November 2005 **/ /** Written by ppk, www.quirksmode.org **/ /** Instructions for use on my site **/ /** **/ /** You may use or change this script **/ /** only when this copyright notice **/ /** is intact. **/ /** **/ /** If you extend the script, please **/ /** add a short description and your **/ /** name below. **/ /*****************************************/ var containerTag = 'TR'; var compatible = ( document.getElementById && document.getElementsByTagName && document.createElement && !(navigator.userAgent.indexOf('MSIE 5') != -1 && navigator.userAgent.indexOf('Mac') != -1) ); if (compatible) { document.write('<style>.accessibility{display: none}</style>'); var waitingRoom = document.createElement('div'); } var hiddenFormFieldsPointers = new Object(); function prepareForm() { if (!compatible) return; var marker = document.createElement(containerTag); marker.style.display = 'none'; var x = document.getElementsByTagName('select'); for (var i=0;i<x.length;i++) addEvent(x[i],'change',showHideFields) var x = document.getElementsByTagName(containerTag); var hiddenFields = new Array; for (var i=0;i<x.length;i++) { if (x[i].getAttribute('rel')) { var y = getAllFormFields(x[i]); x[i].nestedRels = new Array(); for (var j=0;j<y.length;j++) { var rel = y[j].getAttribute('rel'); if (!rel || rel == 'none') continue; x[i].nestedRels.push(rel); } if (!x[i].nestedRels.length) x[i].nestedRels = null; hiddenFields.push(x[i]); } } while (hiddenFields.length) { var rel = hiddenFields[0].getAttribute('rel'); if (!hiddenFormFieldsPointers[rel]) hiddenFormFieldsPointers[rel] = new Array(); var relIndex = hiddenFormFieldsPointers[rel].length; hiddenFormFieldsPointers[rel][relIndex] = hiddenFields[0]; var newMarker = marker.cloneNode(true); newMarker.id = rel + relIndex; hiddenFields[0].parentNode.replaceChild(newMarker,hiddenFields[0]); waitingRoom.appendChild(hiddenFields.shift()); } setDefaults(); addEvent(document,'click',showHideFields); } function setDefaults() { var y = document.getElementsByTagName('input'); for (var i=0;i<y.length;i++) { if (y[i].checked && y[i].getAttribute('rel')) intoMainForm(y[i].getAttribute('rel')) } var z = document.getElementsByTagName('select'); for (var i=0;i<z.length;i++) { if (z[i].options[z[i].selectedIndex].getAttribute('rel')) intoMainForm(z[i].options[z[i].selectedIndex].getAttribute('rel')) } } function showHideFields(e) { if (!e) var e = window.event; var tg = e.target || e.srcElement; if (tg.nodeName == 'LABEL') { var relatedFieldName = tg.getAttribute('for') || tg.getAttribute('htmlFor'); tg = document.getElementById(relatedFieldName); } if ( !(tg.nodeName == 'SELECT' && e.type == 'change') && !(tg.nodeName == 'INPUT' && tg.getAttribute('rel')) ) return; var fieldsToBeInserted = tg.getAttribute('rel'); if (tg.type == 'radio') { removeOthers(tg.form[tg.name],fieldsToBeInserted) intoMainForm(fieldsToBeInserted); } } function removeOthers(others,fieldsToBeInserted) { for (var i=0;i<others.length;i++) { var show = others[i].getAttribute('rel'); if (show == fieldsToBeInserted) continue; intoWaitingRoom(show); } } function intoWaitingRoom(relation) { if (relation == 'none') return; var Elements = hiddenFormFieldsPointers[relation]; for (var i=0;i<Elements.length;i++) { waitingRoom.appendChild(Elements[i]); if (Elements[i].nestedRels) for (var j=0;j<Elements[i].nestedRels.length;j++) intoWaitingRoom(Elements[i].nestedRels[j]); } } function intoMainForm(relation) { if (relation == 'none') return; var Elements = hiddenFormFieldsPointers[relation]; for (var i=0;i<Elements.length;i++) { var insertPoint = document.getElementById(relation+i); insertPoint.parentNode.insertBefore(Elements[i],insertPoint); if (Elements[i].nestedRels) { var fields = getAllFormFields(Elements[i]); for (var j=0;j<fields.length;j++) { if (!fields[j].getAttribute('rel')) continue; if (fields[j].checked || fields[j].selected) intoMainForm(fields[j].getAttribute('rel')); } } } } function getAllFormFields(node) { var allFormFields = new Array; var x = node.getElementsByTagName('input'); for (var i=0;i<x.length;i++) allFormFields.push(x[i]); var y = node.getElementsByTagName('option'); for (var i=0;i<y.length;i++) allFormFields.push(y[i]); return allFormFields; } /** ULTRA-SIMPLE EVENT ADDING **/ function addEvent(obj,type,fn) { if (obj.addEventListener) obj.addEventListener(type,fn,false); else if (obj.attachEvent) obj.attachEvent("on"+type,fn); } addEvent(window,"load",prepareForm); /** PUSH AND SHIFT FOR IE5 **/ function Array_push() { var A_p = 0 for (A_p = 0; A_p < arguments.length; A_p++) { this[this.length] = arguments[A_p] } return this.length } if (typeof Array.prototype.push == "undefined") { Array.prototype.push = Array_push } function Array_shift() { var A_s = 0 var response = this[0] for (A_s = 0; A_s < this.length-1; A_s++) { this[A_s] = this[A_s + 1] } this.length-- return response } if (typeof Array.prototype.shift == "undefined") { Array.prototype.shift = Array_shift } I am finishing up my Form page, and totally forgot to have a numeric only field. So I added it and I can't get it to work. I also am having issues throwing an error when you don't select at least one topping. And are these lines correct? Code: document.cookie = "toppings=" + encodeURIComponent(document.getElementsByName("toppings[]").value); Code: document.cookie = "extra=" + encodeURIComponent(extra); Here is a link to the page hosted on my dropbox http://dl.dropbox.com/u/49211616/dw/...orderPage.html Javascript: Code: function validateOrder () { var crustSelection = document.orderForm.crust.value; var crustPrice; //Adds $1 for Deep DishParmesagn, and Sourdough var count = 0; //Amount of Toppings Selected var choice = ""; //Toppings Selected list var x = ""; //Don't need for the Cookie var extra = 0; //extra charge for toppings over 3 try{ var error = ""; // Initialize Var to store the error messages. if(document.getElementById("delivery").checked != true && document.getElementById("takeout").checked != true) { error=error+"Order Type is required.\n" } if(document.getElementById("fname").value == "") { error = error + "First Name is required.\n"; } if(document.getElementById("lname").value == "") { error = error + "Last Name is required.\n"; } if(document.getElementById("address").value == "") { error = error + "Street address is required.\n"; } if (isNaN(document.getElementById("quantity"))) { error = error + "Enter Pizza Quantity in Numbers Only.\n"; } if(document.getElementById("crust").value == "") { error = error + "Crust Type is required.\n"; } if(document.getElementsByName("toppings").value == 0) { error = error + "Select at Least One Topping.\n"; } if(error == "") { // save all the information in the cookie document.cookie = "firstName=" + encodeURIComponent(document.getElementById("fname").value); document.cookie = "lastName=" + encodeURIComponent(document.getElementById("lname").value); document.cookie = "address=" + encodeURIComponent(document.getElementById("address").value); document.cookie = "order=" + encodeURIComponent((document.getElementById("delivery").checked) ? "delivery" : "takeout"); document.cookie = "quantity=" + encodeURIComponent(document.getElementById("quantity").value); document.cookie = "quantity=" + encodeURIComponent(document.getElementById("quantity").value); document.cookie = "crust=" + encodeURIComponent(document.getElementById("crust").value); document.cookie = "toppings=" + encodeURIComponent(document.getElementsByName("toppings[]").value); alert("Order successfully Placed!"); } else { alert(error); } } catch(ex) { alert("An error occurred!.\n" + "Error Name : " + ex.name + "\nError Message : " + ex.message); } for (var i=1; i<11; i++) { x = document.orderForm['toppings' + i].value; if (document.orderForm['toppings' + i].checked) { choice = choice + " " + x ; count ++; } } if (choice.length <= 0) { choice = choice + "NONE"; } if (count > 3) { extra = (count - 3) * 1 } document.cookie = "extra=" + encodeURIComponent(extra); } </script> HTML: Code: <form name = "orderForm" onsubmit="validateOrder()"> <table width="600" border="0"> <tr> <th scope="col" width="400" align="left"><b>First Name</b><br /><input type="text" id="fname" name="fname" size=30> <br /> <br /> <b>Last Name</b><br /> <input type="text" id="lname" name="lname" size=30> <br /> <br /> <b>Street Address</b><br /> <input type="text" id="address" name="address" size=30> <br /> <br /> <input name="orderType" value="delivery" id="delivery" type="radio">Delivery</font> <input name="orderType" value="takeOut" id="takeout" type="radio">Take Out</font></th> <th scope="col" width="200" align="Left"> How Many Pizzas? <input type="text" id="quantity" name="quantity" size=5> <br /> <br /> <select name="crust" id="crust"> <option selected value="false">Select Crust Type</option> <option value="regular">Regular Crust</option> <option value="thin">Thin Crust</option> <option value="deep">Deep Dish</option> <option value="Parmesagn">Parmesagn Cheese</option> <option value="sourdough">Sourdough</option> </select> <br /> <br /> Select at Least One Topping: <br /> <br /> <input name = "toppings1" type = "checkbox" value = "extraCheese"> Extra Cheese<br> <input name = "toppings2" type = "checkbox" value = "sausage"> Sausage<br> <input name = "toppings3" type = "checkbox" value = "pepperoni"> Pepperoni<br> <input name = "toppings4" type = "checkbox" value = "bacon"> Bacon<br> <input name = "toppings5" type = "checkbox" value = "canadianBacon"> Canadian Bacon<br> <input name = "toppings6" type = "checkbox" value = "mushroom"> Mushroom<br> <input name = "toppings7" type = "checkbox" value = "pineapple"> Pineapple<br> <input name = "toppings8" type = "checkbox" value = "onion"> Onion<br> <input name = "toppings9" type = "checkbox" value = "olive"> Olive<br> <input name = "toppings10" type = "checkbox" value = "greenPepper"> Green Pepper<br></th> </tr> </table> <input name="submit" type="submit" value="submit" /><input name="" type="reset" /> </form> |