JavaScript - Looping Radio Buttons Question
Kind of a novice here, but I've looked and looked... and looked, and can't find an answer to this seemingly simple problem. I apologize in advance:
I'm trying to make it so radio buttons get looped, but have a different name/id each time through the loop. The code below is exactly what I need to do, but the problem is that in each loop, the radio button has the same name/id, so it only selects one button at a time. How do I fix that? Thanks! Code: <html> <body> <script type="text/javascript"> for (i = 0; i <= 5; i++) { document.write("<input type='radio' id='qg1' name='q1' value='Great' />Great!</> :: <input type='radio' id='qg1' name='q1' value='Good' />Good!</>"); document.write("<br />"); } </script> <p>This for loop starts with i=0.</p> <p>As long as <b>i</b> is less than, or equal to 5, the loop will continue to run.</p> </body> </html> Similar Tutorialshello, this is my first attempt in javascript. im trying to make custom radio buttons here is the code i have: Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <title>Untitled Document</title> <style type="text/css"> .hide {display:none;} .radio {width:16px;height:16px;} </style> <script type="text/javascript"> // declare variables or different states var off = 'images/check-off.png'; var on = 'images/check-on.png'; var radioImage = document.createElement('img'); function replaceRadios(){ var radios = document.getElementsByName('radio1'); radios.type = 'radio' for (r = 1; r < radios.length; r++) { // if radio is checked configure the img src to var on if (radios[r].type = 'radio' && radios[r].checked) { radioImage.src = on; radioImage.className= 'radio on'; } else { // otherwise configure the img src to var normal/off and give it a class of radio radioImage.src = off; radioImage.className= 'radio off'; } // give the image an id of radio radioImage.className = 'radio'; radioImage.onclick= radioStates; radios[r].parentNode.insertBefore(radioImage,radios[r]); // hide the radio button to show image radios[r].className = 'hide'; } } function radioStates(r) { var radios = document.getElementsByName('radio1'); if (radios.checked = true) { radioImage.setAttribute("class", "radio on"); radioImage.src = on; } else if (radios.checked = false) { radioImage.setAttribute("class", "radio off"); radioImage.src = off; } else { radioImage.setAttribute("class", "radio off"); radioImage.src = off; } } setTimeout("replaceRadios()", 0); </script> </head> <body> <form name="radiotest"> <input type="radio" id="radio1" class="radio" name="radio1" /> <input type="radio" id="radio2" class="radio" name="radio1" /> <input type="submit" id="submit" name="submit" /> </form> </body> </html> If anyone could help me, I would greatly appreciate it. On my website I have a radio button as any other normal radio button. <input type="radio" name="crime" value="4" id="4" class="submit"> is there any way to get rid of this radio button and click something for example <tr> <td>Blah blah</td> <td>Blah Blah</td> </tr> is there any code i can put in the <tr> tag so if i click that section it will act as a radio button and when its selected change the background of the tr section. I'm creating a unit converter program using radio buttons and i can't seem to get one aspect working. i can't seem to get another set of radio buttons to display. the way the program is supposed to work is there will be 3 radio buttons saying to convert length, weight, and volume. if the user selects to convert weight, another set of radio buttons will appear with 2 options, to convert from pounds to kilograms, or kilograms to pounds. then the user enters the number in a text box and clicks to convert button. my problem is getting the second set of radio buttons to display. I have no clue how to get this to work. to get a better understanding of whats going on, here is the program without the radio buttons that i created. i'm trying to use radio buttons in place of the prompting message. Code: <!DOCTYPE html> <html> <head> <title> Conversions of Weight and Length</title> <script type="text/javascript"> function clearMe() { var _s=top; var _d=_s.document; _d.open(); _d.write(""); _d.close(); } function main() { var repeat = confirm("Do you want to perform another conversion ? \r" + "<p><b>Note:</b> Pressing OK allows for another conversion, and pressing CANCEL exits</p>"); if(repeat==true) { convert(); } else { alert("Your program has been terminated!"); self.close(); } } function convert() { var unit, direction, value, result, original_units, new_units; document.write("<br/><br/>") document.write("Weight and Length conversion menu" + "<br/><br/>"); document.write("1. convert length" + "<br />"); document.write("2. convert weight" + "<br />"); document.write("3. convert volume" + "<br />"); unit = window.prompt("select conversion type: "); if ((unit<0) || (unit>3)) { alert("Select Menu option 1, 2, or 3!"); unit = window.prompt("Select conversion type: "); } switch (unit) { case '1': direction = choose_direction("<br /><br />1. Feet to meters<br />" , "2. Meters to feet <br />"); if (direction =='1') { original_units = "meters"; new_units = "meters"; } else { new_units = "feet"; original_units = "meters"; } break; case '2': direction = choose_direction("<br /><br />1. Pounds to kilograms <br />", "2. Kilograms to pounds <br /> <br />"); if (direction =='1') { original_units = "pounds"; new_units = "kilograms"; } else { new_units = "pounds"; original_units = "kilograms"; } break; case '3': direction = choose_direction("<br /><br />1. Gallons to liters<br />", "2. Liters to gallons <br /><br />"); if (direction =='1') { original_units = "gallons"; new_units = "liters"; } else { new_units = "gallons"; original_units = "liters"; } break; } value = window.prompt("Enter value to be converted:") switch(unit) { case '1': result = feet_meters(value, direction); break; case '2': result = pounds_kilograms(value, direction); break; case '3': result = gallons_liters(value, direction); break; } document.write(value + original_units + " = " + result + new_units); } function choose_direction(option1, option2) { var direction; document.write(option1); document.write(option2); do { window.prompt("Select a conversion direction"); return direction; } while ((direction!='1') || (direction !='2')); } function pounds_kilograms(value, direction) { if (direction == '1') return parseFloat(value)/parseFloat(2.2046); else return parseFloat(value)*parseFloat(2.2046); } function gallons_liters(value, direction) { if (direction == '1') return parseFloat(value)*parseFloat(3.7854); else return parseFloat(value)/parseFloat(3.7854); } function feet_meters(value, direction) { if (direction == '1') return parseFloat(value)/parseFloat(3.2808); else return parseFloat(value)*parseFloat(3.2808); } </script> </head> <body> <h1> weight and length conversion </h1> <script type="text/javascript"> convert(); main(); </script> </body> </html> I'm Confused. My HTML: <form action="mail.php" class="contactForm" name="cform" method="post"> <div class="left"> <h1>Insurance Details</h1> <label>Type of Cover:</label> . . . <span class="gender-missing"><br />Please select your gender.<br /></span> <label>Gender:</label> <input class="radio" id="gender" name="gender" type="radio" value="Male" /> Male <input class="radio" id="gender" name="gender" type="radio" value="Female" /> Female Script.js: $('.contactForm').submit( function(){ //statements to validate the form var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; var digitNum = /^([0-9])/; var num1 = document.getElementById('tel'); var num2 = document.getElementById('mobile'); var email = document.getElementById('email'); var dollarUnit = document.getElementById('amount_cover'); var gender = document.getElementsById('gender'); if((document.cform.gender[0].checked== false)&&(document.cform.gender[1].checked== false)) {$('.gender-missing').show(); } else {$('.gender-missing').hide();} if((document.cform.smoke[0].checked== false)&&(document.cform.smoke[1].checked== false)) {$('.smoke-missing').show(); } else {$('.smoke-missing').hide();} if((document.cform.residency[0].checked== false)&&(document.cform.residency[1].checked== false)) {$('.residency-missing').show(); } else {$('.residency-missing').hide();} if (!filter.test(email.value)) { $('.email-missing').show(); } else {$('.email-missing').hide();} if (document.cform.name.value == "") { $('.name-missing').show(); } else {$('.name-missing').hide();} if (document.cform.address.value == "") { $('.address-missing').show(); } else {$('.address-missing').hide();} if (!digitNum.test(num1.value)) { $('.tel-missing').show(); } else {$('.tel-missing').hide();} if (!digitNum.test(num2.value)) { $('.mobile-missing').show(); } else {$('.mobile-missing').hide();} if (!digitNum.test(dollarUnit.value)) { $('.cover-missing').show(); } else {$('.cover-missing').hide();} if (document.cform.message.value == "") { $('.message-missing').show(); } else {$('.message-missing').hide();} if ((document.cform.name.value == "") || ((document.cform.gender[0].checked== false) && (document.cform.gender[1].checked== false)) || ((document.cform.smoke[0].checked== false) && (document.cform.smoke[1].checked== false)) || ((document.cform.residency[0].checked== false) && (document.cform.residency[1].checked== false)) || (!digitNum.test(dollarUnit.value)) || (!filter.test(email.value)) || (!digitNum.test(num2.value)) || (!digitNum.test(num1.value)) || (document.cform.message.value == "")){ return false; } if ((document.cform.name.value != "") && ((document.cform.gender[0].checked == true) || (document.cform.gender[1].checked == true)) && ((document.cform.smoke[0].checked== true) || (document.cform.smoke[1].checked== true)) && ((document.cform.residency[0].checked== true) || (document.cform.residency[1].checked== true)) && (digitNum.test(dollarUnit.value)) && (digitNum.test(num1.value)) && (digitNum.test(num2.value)) && (filter.test(email.value)) && (document.cform.message.value != "")) { //hide the form $('.contactForm').hide(); //show the loading bar $('.loader').append($('.bar')); $('.bar').css({display:'block'}); //send the ajax request $.post('mail.php',{coverType:$('#coverType').val(), coverRequired:$('#coverRequired').val(), amount_cover:$('#amount_cover').val(), terms:$('#terms').val(), message:$('#message').val(), name:$('#name').val(), gender:$('#gender').val(), status:$('#status').val(), Birth_month:$('#Birth_month').val(), days:$('#days').val(), years:$('#years').val(), smoke:$('#smoke').val(), residency:$('#residency').val(), email:$('#email').val(), address:$('#address').val(), tel:$('#tel').val(), mobile:$('#mobile').val()}, //return the data function(data){ //hide the graphic $('.bar').css({display:'none'}); $('.loader').append(data); }); //waits 2000, then closes the form and fades out setTimeout('$("#backgroundPopup").fadeOut("slow"); $("#contactForm").slideUp("slow")', 5000); setTimeout('$(".contact").animate({"marginLeft": "-=963px"}, "slow")',4900); //stay on the page return false; } }); //only need force for IE6 $("#backgroundPopup").css({ "height": document.documentElement.clientHeight }); mail.php code: <?php //declare our variables $coverType = $_POST['coverType']; $coverRequired = $_POST['coverRequired']; $amount_cover = $_POST['amount_cover']; $terms = $_POST['terms']; $message = stripslashes(nl2br($_POST['message'])); $name = $_POST['name']; $gender = $_POST['gender']; $status = $_POST['status']; $Birth_month = $_POST['Birth_month']; $days = $_POST['days']; $years = $_POST['years']; $smoke = $_POST['smoke']; $residency = $_POST['residency']; $email = $_POST['email']; $address = $_POST['address']; $tel = $_POST['tel']; $mobile = $_POST['mobile']; //get todays date $todayis = date("l, F j, Y, g:i a") ; //set a title for the message $subject = "Message from Your Website"; $body = "PERSONAL DETAILS \nFull Name: $name \nGender: $gender \nMarital Status: $status \nBirth Date: $Birth_month $days, $years \nHave you smoke in the past 12 Months? $smoke \nU.S. Residency for at least 12 Months? $residency \n\nCONTACT DETAILS\nEmail Address: $email \nAddress: $address \nTelephone #: $tel \nMobile Number: $mobile \n\nINSURANCE DETAILS\nCover Type: $coverType \nCover Required: $coverRequired \nAmount: $amount_cover \nTerms(Years): $terms \nMessage: \n$message"; $headers = 'From: '.$email.'' . "\r\n" . 'Reply-To: '.$email.'' . "\r\n" . 'Content-type: text/plain; charset=utf-8' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); //put your email address here mail("me@myemail.com", $subject, $body, $headers); ?> <!--Display a thankyou message in the callback --> <div id="mail_response"> <h3>Thank you for your interest <?php echo $name ?>!</h3><br /> <p>We have received your personal information and we will forward it to the next available insurance agent .You can expect to hear from us within 24 hours.</p> <br /><br /> <h5>Message sent on: </h5> <p><?php echo $todayis ?></p> </div> Problem is the thank you message loads in a new page. BUt if I delete this line: var gender = document.getElementsById('gender'); The form run properly, when submit button is click, it will hide the forms and replace by a thank you message but problem is the data send in the email is not the right value eg. in Gender: I select Female. BUt I receive Male as value. Why is that? for live demo: http://gbv.lifeandhealthbenefits.com/ for full Script Code: http://gbv.lifeandhealthbenefits.com/js/scripts.js Im trying to configuere a form that a. a radio buttons that allow the user to choose between quarters, nickels, dimes and pennies. and show image when click on my radio button im confused on how to get the image to display whenthey click on the radio button On my website I have a radio button as any other normal radio button. <input type="radio" name="crime" value="4" id="4" class="submit"> is there any way to get rid of this radio button and click something for example <tr> <td>Blah blah</td> <td>Blah Blah</td> </tr> is there any code i can put in the <tr> tag so if i click that section it will act as a radio button and when its selected change the background of the tr section. I've been looking around and all the validation stuff I've seen doesn't work for what I have. Here is what I am trying to do: The user selects the Heads or Tails radio button for the first flip and then selects heads or tails radio button for the 2nd flip. The script then randomly flips two coins and compares it to what the user selected and if they are the same the user wins and if not then they lose. So there would be 4 buttons total, two Heads and two Tails. The first set of Heads and Tails needs to be assigned to "guess1" and the 2nd set is "guess2". So if the user clicks Tails for Flip1 and Heads for Flip2 then Tails is assigned to guess1 and Heads is assigned to guess2. Right now the script just assumes the user is selecting heads for both flips. Code: <html> <head> <title>Guess Two Coin Tosses</title> <script> function flip5(){ //Input var guess1 = document.getElementById('guess1').value var guess2 = document.getElementById('guess2').value var flip1 = Math.floor(Math.random() * 2) var flip2 = Math.floor(Math.random() * 2) var outcomes if (flip1 == 0) flip1 = 'Heads'; else flip1 = 'Tails'; if (flip2 == 0) flip2 = 'Heads'; else flip2 = 'Tails'; //Processing if (flip1.toUpperCase() == guess1.toUpperCase()) { if (flip2.toUpperCase() == guess2.toUpperCase()) outcomes = 'win win'; else outcomes = 'win lose'; } else { // here we lost the first if (flip2.toUpperCase() == guess2.toUpperCase()) outcomes = 'lose win'; else outcomes = 'lose lose'; } //Output document.getElementById('flip1').value = flip1 document.getElementById('flip2').value = flip2 document.getElementById('outcomes').value = outcomes } </script> </head> <body> <h3>Predict the Futu Guess Two Coin Flips</h3> Enter Heads for Heads, Tails for Tails! Case does not matter! <p/>Your Guess for Flip-1: <input type=radio id="guess1" size="5" value="Heads" />Heads <input type=radio id="guess1" size="5" value="Tails" />Tails <p/>Your Guess for Flip-2: <input type=radio id="guess2" size="5" value="Heads" />Heads <input type=radio id="guess2" size="5" value="Tails" />Tails <p/>Flip-1: <input type="text" id="flip1" size="5" value="???" /> <p/>Flip-2: <input type="text" id="flip2" size="5" value="???" /> <p/><input type="button" value="Flip Two!" onclick="flip5()" /> <p/>Outcomes: <input type="text" id="outcomes" size="20" value="" /> <hr> </body> </html> Just wondering what the code would be to validate the radio buttons, thus when i click get score a pop up will tell me that one of the radio buttons was not selected. If you really want to help me it would be good if i was able to have get score and submit working on one button, and validating every field. My code is below (don't mind the questions and answers ) Code: <HEAD> <script language="JavaScript"> var numQues = 5; var numChoi = 3; var answers = new Array(5); answers[0] = "Life"; answers[1] = "Disturbing"; answers[2] = "Yahoo Answers"; answers[3] = "Playing Video Games in the Basement"; answers[4] = "About the portion of my Sandwich"; function getScore(form) { var score = 0; var currElt; var currSelection; for (i=0; i<numQues; i++) { currElt = i*numChoi; for (j=0; j<numChoi; j++) { currSelection = form.elements[currElt + j]; if (currSelection.checked) { if (currSelection.value == answers[i]) { score++; break; } } } } score = Math.round(score/numQues*100); form.percentage.value = score + "%"; var correctAnswers = ""; for (i=1; i<=numQues; i++) { correctAnswers += i + ". " + answers[i-1] + "\r\n"; } form.solutions.value = correctAnswers; } function validate_required(field,alerttxt) { with (field) { if (value==null||value=="") { alert(alerttxt);return false; } else { return true; } } } function echeck(str) { var at="@" var dot="." var lat=str.indexOf(at) var lstr=str.length var ldot=str.indexOf(dot) if (str.indexOf(at)==-1){ alert("Please Enter a Valid E-mail") return false } if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){ alert("Please Enter a Valid E-mail") return false } if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){ alert("Please Enter a Valid E-mail") return false } if (str.indexOf(at,(lat+1))!=-1){ alert("Please Enter a Valid E-mail") return false } if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){ alert("Please Enter a Valid E-mail") return false } if (str.indexOf(dot,(lat+2))==-1){ alert("Please Enter a Valid E-mail") return false } if (str.indexOf(" ")!=-1){ alert("Please Enter a Valid E-mail") return false } return true } function validate_form(thisform) { with (thisform) { if (validate_required(Name,"Name must be filled out!")==false) {Name.focus();return false;} if (validate_required(Surname,"Surname must be filled out!")==false) {Surname.focus();return false;} { var emailID=document.submitting.email if ((emailID.value==null)||(emailID.value=="")){ alert("Please Enter a Valid E-mail") emailID.focus() return false } if (echeck(emailID.value)==false){ emailID.value="" emailID.focus() return false } return true } } } </script> </HEAD> <BODY> <h3>Quiz</h3> <form name="quiz"> 1. What do i win at..? <ul style="margin-top: 1pt"> <li><input type="radio" name="q1" value="Life">Life</li> <li><input type="radio" name="q1" value="Nothing At All">Nothing At All</li> <li><input type="radio" name="q1" value="Using a Computer">Using a Computer</li> </ul> 2. My Life is..? <ul style="margin-top: 1pt"> <li><input type="radio" name="q2" value="Boring">Boring</li> <li><input type="radio" name="q2" value="Disturbing">Disturbing</li> <li><input type="radio" name="q2" value="Like everyone elses">Like everyone elses</li> </ul> 3. I don't learn off my mother i learn off ..? <ul style="margin-top: 1pt"> <li><input type="radio" name="q3" value="Google">Google</li> <li><input type="radio" name="q3" value="Yahoo Answers">Yahoo Answers</li> <li><input type="radio" name="q3" value="The Bible">The Bible</li> </ul> 4. I Spend Most of my time ..? <ul style="margin-top: 1pt"> <li><input type="radio" name="q4" value="Cutting Down Palm Tree's">Cutting Down Palm Tree's</li> <li><input type="radio" name="q4" value="Eating">Eating</li> <li><input type="radio" name="q4" value="Playing Video Games in the Basement">Playing Video Games in the Basement</li> </ul> 5. I Complain the most about ..? <ul style="margin-top: 1pt"> <li><input type="radio" name="q5" value="JavaScript">JavaScript</li> <li><input type="radio" name="q5" value="About the portion of my Sandwich">About the portion of my Sandwich</li> <li><input type="radio" name="q5" value="Lag">Lag</li> </ul> <input type="button" value="Get score" onClick="getScore(this.form)"> <input type="reset" value="Clear answers"> <p> Score = <strong><input class="bgclr" type="text" size="5" name="percentage" disabled></strong><br><br> Correct answers:<br> <textarea class="bgclr" name="solutions" wrap="virtual" rows="4" cols="30" disabled> </textarea> </form> <form action="submit.htm" onsubmit="return validate_form(this)" method="post" name="submitting"> Name: <input type="text" name="Name" size="30"> <br> <br> Surname: <input type="text" name="Surname" size="30"><br><br> Email: <input type="text" name="email" size="30"><br> <form action="submit.htm" onSubmit="return validate_form(this)" method="post"> <input type="submit" value="Submit" > </form> </body> Hello, I'm currently trying to figure out how I can make each radio button call a different page. For example If i click on radio button 1 and click submit it will take me to www.website1.com and if I click radio button 2 and click submit it will take me to www.website2.com. I would really appreciate your help Thank you Eric Originally I had the following code. What it does is for a user to type the folder name of their choice and then after clicking submit a window will pop open and they will be taken to "C:\folder" (assuming the user typed "folder" and such a folder existed). Here is the code in case I wasn't clear. Code: <html> <head> <script type="text/javascript"> function goTo() { var drive = document.forms[0].drive.value; var folder = document.forms[0].folder.value; window.location = drive+folder; return false; } </script> </head> <body> <center> <b><u>Folder Search</u></b> <form action="" method="get" onsubmit="return goTo()"> Choose drive: <input type="hidden" name="drive" id="drive" value="C:\"> <br> Enter folder name: <input type="text" name="folder" id="folder"> <p> <input type="submit" value="Submit"> </form> </center> </body> </html> However, what I want to do now is change it so that the user can click on radio buttons to choose the drive they want. I realize I could use the code above and have the user type in the drive they want but I would rather have radio buttons for them to choose. Here is what I have so far. Code: <html> <head> <script type="text/javascript"> function goTo() { var drive = document.forms[0].drive[i].value; var file = document.forms[0].file.value; window.location = drive+folder; return false; } </script> </head> <body> <form method="get" action="" onsubmit="return goTo()"> Choose Drive: <input type="radio" name="drive" id="C Drive" value="C:\">C Drive <input type="radio" name="drive" id="D Drive" value="D:\">D Drive <input type="radio" name="drive" id="F Drive" value="F:\">F Drive <br> Enter Folder Name: <input type="text" name="folder" id="folder"> <p> <input type="submit" value="Submit"> </form> </body> </html> Now after the user clicks submit nothing really happens. I'm a real n00b at this. I could use some help. Thanks in advance. Hi.. I have 2 groups of radio buttons.. I can manage to make one set be disabled via a selection.. but i can only get this right with the VALUE... Is it possible to use the radio id to do the same?? Just use the link below for they jquery <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> Code: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <script src="jquery.min.js"></script> </head> <body> <br /> <br /> <div> 1 - <input type="radio" id="1" value="11" /> </div> <div> 2 - <input type="radio" id="2" value="22"/> </div> <div> 3 - <input type="radio" id="3" value="33"/> </div> <br /> <br /> <div> 1 - <input type="radio" id="1" value="11" /> </div> <div> 2 - <input type="radio" id="2" value="22" /> </div> <div> 3 - <input type="radio" id="3" value="33" /> </div> <script> $("input:radio").click(function() { var val = $(this).val(); $(this).siblings("input:radio").attr("disabled","disabled"); $("input:radio[value='" + val + "']").not(this).attr("disabled","disabled"); }); </script> </body> </html> Hi, I'm a year 11 student studying GCSE computing. I'm doing a project and I need to conduct some primary resarch, so I would be grateful if someone could explain to me how to go about coding radio buttons in a HTML web page which uses JavaScript. Thank you! I can't get the radio buttons to work properly in my browser. If you don't press one the alert box does not tell you that you have to tick either male or female. Also I noticed you can tick both but it won't say you must choose only one, how can I sort this...any help please. case "radio_hidden": if (fld.value != "1")/* radio male or female button should be checked*/ { fld.valid = true; } break; if (frm.radio_hidden.valid == false) { report_text += " You must click a radio button male or female.\n\n" } <br><u>Select Your gender:</u><br> <input type="radio" name="male" value="" onchange="radio_hidden.value = 1;"> Male <br> <input type="radio" name="female" value="" onchange="radio_hidden.value = 1;"> Female <br> <input name="radio_hidden" value="" type="hidden"> 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 All, I wish to allow the use of a checkbox based on which radio button is selected. Pseudo Code: IF RadioButton "Adult_or_Child"= Adult Then Checkbox "Pensioner" = Available to click End IF Else IF RadioButton "Adult_or_Child"= Child Then Checkbox "Pensioner" = Not Available to click. End If As you can see, a person can be an adult and a pensioner but not a child and a pensioner. Thanks for your help. Dan Hello, I'm trying to create a function that will print out: "Nice job!" after a user clicks on a radio button. The code which I have below is my attempt, but I fear that nothing happens. Code: $(':radio').click(function() { if ($(this).attr('checked')) { $('#show_response').innerHTML = 'Nice Job';}}) } Within my html I have: Code: <span id="show_response"></span> right next to the radio buttons of interest. However, nothing happens when I view my page. Any thoughts on this would be most appreciated. Thank you... I have 5 radio buttons called A, B, C, D, and E in my html file. I need to validate them using javascript. If no radio buttons are selected, then a message should come up and say "none selected". I actually got this part done, and it works. However, I need to do one more thing. If radio button E and any other radio button(s) are selected simultaneously, then an error message should pop up and say "Wrong combinations." How should I go about doing this? I think I'll need a logical function to do this... thanks for any help! I think I have a fairly simple question. I'm trying to set the values of Radio buttons, check boxes and drop down lists so my users can go back and edit the form for a certain amount of time. So far it only saves text box values I tried to implement the radio buttons in there but it doesn't work. What do I need to do so that radio buttons, check boxes and drop down list values are all saved? Javascript: Code: <script> /** * Set a cookie * @param string cookie name * @param string cookie value * @param string cookie expiration counter in days * @param string cookie path * @param string cookie domain * @param bool secure?*/ function setCookie( name, value, expires, path, domain, secure ) { var today = new Date(); today.setTime( today.getTime() ); if ( expires ) { expires = expires * 5 * 60; } var expires_date = new Date( today.getTime() + (expires) ); document.cookie = name+"="+escape( value ) + ( ( expires ) ? ";expires="+expires_date.toGMTString() : "" ) + ( ( path ) ? ";path=" + path : "" ) + ( ( domain ) ? ";domain=" + domain : "" ) + ( ( secure ) ? ";secure" : "" ); } /* * Get a cookie value * @param string cookie name*/ function getCookie( name ) { var start = document.cookie.indexOf( name + "=" ); var len = start + name.length + 1; if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) { return null; } if ( start == -1 ) return null; var end = document.cookie.indexOf( ";", len ); if ( end == -1 ) end = document.cookie.length; return unescape( document.cookie.substring( len, end ) ); } /** * Remebers form inputs after you fill them in * @param string a prefix to prepend to all cookie names. (prevent naming conflicts)*/ function rememberFormInputs(form_id, prefix) { // get a reference to the form element with id 'form_test' var form = document.getElementById(form_id); // get all child input elements of the form var els = document.getElementsByTagName('input'); // iterate through all form child input elements for (var i = 0; i < els.length; i++) { // this is the element with index of i var el = els.item(i); // make sure this is a text input field if (el.type == 'text' || el.type == 'radio' || el.type == 'checkbox') { // event handler to catch onblur events // it sets the cookie values each time you move out of an input field el.onblur = function() { // this is the name of the input field var name = this.name; // this is the value of the input field var value = this.value; // set the cookie setCookie( prefix + name, value); alert('setCookie: '+name + ' = '+value); }; // this inserts all the remembered cookie values into the input fields var old_value = getCookie(prefix + el.name); if (old_value && old_value != '') { alert('old value remembered: '+old_value); el.value = old_value; } } } } // function will be run after window/document loads window.onload = function() { rememberFormInputs('form_test', 'input-'); } // overload alert function alert(str) { var el = document.getElementById('alert'); if (el) { el.value += str+"\r\n"; } } </script> HTML: Code: <select name="Refrigerant_Type" > <option value="">Please Select Refrigerant Type</option> <option value="R-22">R-22</option> <option value="R-410 A">R-410 A</option> <option value="R-134 A">R-134 A</option> <option value="R-409 A">R-409 A</option> <option value="R-418 A">R-418 A</option> <option value="R-404 A">R-404 A</option> </select> <br /> <input type="text" name="Lubricant" /> <br /> <input type="radio" value="Comfort" name="Duty" class="radio" /> Comfort <input type="radio" value="Commercial" name="Duty" class="radio" /> Commercial <input type="radio" value="Under" name="Duty" class="radio" /> Under 50lbs <input type="radio" value="Other" name="Duty" class="radio" /> Other <br /> <input type="checkbox" name="New1" value="Yes" /> New<br /> <input type="checkbox" name="RecoveredNew1" value="Yes" /> Recovered<br /> 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? |