JavaScript - How To Print The Value Of A Radio Button In A Javascript Validation
Hello All.
What my script does is if you do not select a radio button and you hit submit an error will pop up saying please select game1. this is taken from the name of the radio button.. How can i make it so it prints out the VALUES of the 2 radio buttons. end result should print please select Baltimore Ravens vs. Cincinnati Bengals rather than please select game1. Code: function isChecked(radgrp) { var i = radgrp.length; do if (radgrp[--i].checked) return true; while (i); return false; } function validateTest(els) { var focus_me = null, msg = ""; if (!isChecked(els.game1)) { msg += " Game #1\n"; focus_me = focus_me || els.game1[0]; } if (!isChecked(els.game2)) { msg += " Game #2\n"; focus_me = focus_me || els.game2[0]; } if (!isChecked(els.game16)) { msg += " Game #16\n"; focus_me = focus_me || els.game16[0]; } if (msg != "") { var prefix = "\n WARNING: The following Games(s) were not selected:\n\n"; var suffix = "\nClick OK to submit your picks anyway.\n\n"; var suffix = suffix + "\n Click CANCEL to correct your picks." var ask = confirm(prefix + msg + suffix); if (ask) { if (focus_me) focus_me.focus(); return true; } else{ return false; } } } Here is the radio button. If you dont select the radio button i want the javascript validation pop but to say "please select Baltimore Ravens vs. Cincinnati Bengals rather than game1 like it does now. Code: <INPUT TYPE=RADIO NAME="game1" VALUE="Baltimore Ravens">Baltimore Ravens<BR> <INPUT TYPE=RADIO NAME="game1" VALUE="Cincinnati Bengals">Cincinnati Bengals<BR> Thanks Similar TutorialsI am using ASP validators and I have a contact form. I want to be able to have a phone and email radio button group. The email textbox also has a RegularExpressionValidator If the phone item is selected then I want the validation to be enabled on the phone text box making it mandatory while the email text box isn't, and if they choose the email as the contact it will be reversed. I want to be able to do this without having to do a postback. I already have the logic on the code behind and the enquiry object. also I am fairly new to javascript so I have been using mostly jQuery as easier to implement 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 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;} } 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'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'm only validating one (Consent) radio button with this code but i need to validate multiple different questions/buttons. Code: <script> function getRBtnName(GrpName) { var sel = document.getElementsByName(GrpName); var fnd = -1; var str = ''; for (var i=0; i<sel.length; i++) { if (sel[i].checked == true) { str = sel[i].value; fnd = i; } } return fnd; } function checkForm() { var chosen = getRBtnName('Consent'); if (chosen < 0) { alert( "Please choose one answer when you are asked to select a number." ); return false; } else { return true; } } </script> <form action="congratulations_aff.php" method="post" name="congratulations_aff" onSubmit="return checkForm()"> <table border="0" cellspacing="1" cellpadding="0"> <tr> <td colspan="3">I consent to providing my electronic signature.</p></td> </tr> <tr> <td colspan="3" valign="top"> <input type="radio" name="Consent" value="Y" /> Yes <input type="radio" name="Consent" value="N" /> No <table border="0" cellspacing="1" cellpadding="0"> <tr> <td>I consent to electronic receipt of my information reporting documentation.</td> </tr> <tr> <td valign="top"> <input type="radio" name="Consent1099YesNo" value="Y" /> Yes <input type="radio" name="Consent1099YesNo" value="N" /> No</td> </tr> <tr> <td valign="top"> For tax purposes are you a U.S. citizen, U.S. resident, U.S. partnership, or U.S. corporation? <input type="radio" name="USPersonYesNo" value="Y" /> Yes <input type="radio" name="USPersonYesNo" value="N" /> No</tr> </table> <input type="submit" value="submit" value="Submit" /> </form> Any help would be greatly appreciated. here is the html code that i have PHP Code: <td valign="middle" valign="middle"> <input type="radio" name="gender" id="genderM" value="Male" /> Male <input type="radio" name="gender" id="genderFM" value="Female" /> Female </td> and here is the js funtion PHP Code: var $j = jQuery.noConflict(); function isValidEmail(str) { return (str.indexOf(".") > 2) && (str.indexOf("@") > 0); } function validateForm(){ var firstName; var lastName; var email; var mobile; var comment; var error; firstName = $j('#firstName').val(); lastName = $j('#lastName').val(); email = $j('#email').val(); mobile = $j('#mobile').val(); comment = $j('#comment').val(); if(firstName=='' || firstName.length < 3){ error = 'Please Enter Your First Name'; $j('#errormsg').html('<p class="errors">'+ error +'</p>'); return false; } if(lastName=='' || lastName.length < 3){ error = 'Please Enter Your Second Name'; $j('#errormsg').html('<p class="errors">'+ error +'</p>'); return false; } //mob //$jmob_pattern = '^\d{10}$j'; if(mobile.length != 10 || isNaN(mobile)){ error = 'Please Enter Your Mobile Number'; $j('#errormsg').html('<p class="errors">'+ error +'</p>'); return false; } if(email=='' || !isValidEmail(email)){ error = 'Please Enter Your Email Address'; $j('#errormsg').html('<p class="errors">'+ error +'</p>'); return false; } if(comment.length < 5){ error = 'Please Enter A Comment'; $j('#errormsg').html('<p class="errors">'+ error +'</p>'); return false; } return true; } Does anybody know how i check to see if the radio button is select and also can anybody tell me how i can check for an email in the correct format the function isValidEmail in the above alows emails to pass through if they are in this format aaa@aaa. i only want them to go through if they are aaa@aaa.com Thanks for your help if you give it Hi guys, I am working on my first validation form and although the Submit button works fine and puts me to the landing page, I don't get the alert, when nothing is checked. Please look at my code and help if you can. I really don't need anything fancy, just working 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" /> <meta name="keywords" content="social media survey, social media, media survey, survey, danish media, danish media survey" /> <meta name="description" content="This survey is a school project, not an actual research. It has been designed to figure out the connection between the gender of the Danish users and their knowledge and usage of social media." /> <script language="JavaScript" type="text/javascript"></script> <script> function isRadioButtonSelected(radioGrpName, errorMsg){ var radios = document.getElementsByName(radioGrpName); var i; for (i=0; i<radios.length; i=i+1 ){ if (radios[i].checked){ return true; } } alert(errorMsg); return false; } function validate(){ if(isRadioButtonSelected('gender', 'please select your gender')){ return true; } return false; } </script> <title>The Social Media survey</title> <style type="text/css"> <!-- body { font: 100%/1.4 Verdana, Arial, Helvetica, sans-serif; background: #8DC63F; margin: 0; padding: 0; color: #000; } } a img { border: none; } .container { width: 960px; margin: 0 auto; } .header { background: #FFF; margin-top: 30px; background-color:transparent; background-image:url(header.jpg); background-attachment: fixed; background-position:left center; background-repeat:no-repeat; } .content { padding-left: 50px; padding-right: 50px; padding-top: 30px; padding-bottom: 30px; background-color:#E7EFB9; font-family:Verdana, Geneva, sans-serif; font-size: 13px; } .footer { background: #FFF; } .fltrt { float: right; margin-left: 8px; } .fltlft { float: left; margin-right: 8px; } .clearfloat { clear:both; height:0; font-size: 1px; line-height: 0px; } </style> </head> <body> <div class="container"> <div class="header"><img src="header1.jpg" alt="The Social Media survey" width="960" height="175" /></div> <div class="content"> <form id="page1" action="http://projects.knord.dk/interaction/saveforminfo.aspx" onsubmit="return validate(); method="post"> <input type="hidden" name="surveyid" value="igakotra" /> <input type="hidden" name="landingpage" value="http://www.google.com" /> <input type="hidden" name="usecookie" value="true" /> <h3>1. Choose your gender</h3> <input type="radio" name="gender" value="male" id="male"/><label for "male">Male</label> <input type="radio" name="gender" value="female" id="female"/><label for "female">Female</label><br /><br /> <input type="submit" name="submit" value="Submit"/> </form> </div> <div class="footer"><a href="page1.html"><img src="1page.jpg" width="960" height="99" alt="1/6 pages" /></div> </div> </body> </html> I really need it asap... thanks guys, you're awesome Hello, I am trying to implement a radio button option so that users can search specific sites such as google, yahoo, or bing from input box. Here's my code. Please help. <script type="text/javascript"> <!-- function goSearch(){ //search according to checked radio button } --> </script> <h1>Search Option</h1><br /> <input type="radio" name="search" id="google"/><a href="http://www.google.com" rel="nofollow" target="_blank"><img src="images/google.jpg" /></a> <input type="radio" name="search" id="yahoo"/><a href="http://www.yahoo.com" rel="nofollow" target="_blank"><img src="images/yahoo.jpg" /> </a> <input type="radio" name="search" id="bing" /><a href="http://www.bing.com" rel="nofollow" target="_blank"><img src="images/bing.jpg" /> </a> <br /><br /> <form method="get" action="goSearch()" rel="nofollow" target="_blank"> <div style="border:1px solid black;padding:4px;width:20em;"> <table border="0" cellpadding="0"> <tr> <td> <input type="text" name="q" size="25" maxlength="255" value="" /> <input type="submit" value="Search" /> </td> </tr> </table> </div> </form> I'm trying to make radiobuttons with a javascript function that gets called when a button is selected to make an image appear depending on what they click. However, after looking it up for a while I have nothing since some tell me to do document.formName.name.value; some tell me to use an id with my buttons and just use a document.getElementByID(""); etc. This is for a project and we havent used parameters yet and I dont know how to implement them in the HTML as well This is my code: function classchoice() { if(document.getElementById('mage') == true) { classtype = "<img class='display' src='mage.jpg'>"; document.getElementById("picture").innerHTML=classtype; } if(document.classes.classes.paladin == true) { classtype = "<img class='display' src='paladin.jpg'>"; document.getElementById("picture").innerHTML=classtype; } if(document.classes.classes.hunter == true) { classtype = "<img class='display' src='hunter.jpg'>"; document.getElementById("picture").innerHTML=classtype; } if(document.classes.classes.rogue == true) { classtype = "<img class='display' src='rogue.jpg'>"; document.getElementById("picture").innerHTML=classtype; } } This is the HTML: <form name="classes"> <input type="radio" name = "classes" id="mage" onmousedown="classChoice();"> <img src = "mage.jpg" /> <input type="radio" name = "classes" id = "Paladin" onmousedown="classChoice();"> <img src = "Paladin.png" /> <input type="radio" name = "classes" id = "hunter" onmousedown="classChoice();"> <img src = "hunter.PNG" /> <input type="radio" name = "classes" id = "rogue" onmousedown="classChoice();"> <img src = "rogue.jpg" /> </form> I hope it's readable because I copy and pasted my code and the indentations are a bit messed up I want to change radio button values dependent on the selected item in a drop down list. The radio buttons have default values but I need them to be changed when the selection has been made in the drop down list and before the submit button has been pressed so the changed values will be written to the database. Example : Drop down item : National Radio 1 value : Director Radio 2 value : National PA Drop down item : Regional Radio 1 value : Regional Manager Radio 2 value : Regional PA Drop down item : Local Radio 1 value : Store Manager Radio 2 value : Assistant Store Manager Any help will be appreciated. I am very new Beginner of Javascript.. My query is that 1)I have 2 radio buttons A and B 2)When I click A I want 2 dropdownbox and a button to be displayed 3)When I click B I want 2 dropdownbox to be displayed. 4)Both should be independent Plz tell me the code..for this I have 4 rows in a table. Each row consist of 4 radio buttons. Each radio button per row has different values in it but has the same name (group) ex: <input type="radio" name="a" value="1"> <input type="radio" name="a" value="2"> <input type="radio" name="a" value="3"> <input type="radio" name="a" value="4"> <input type="radio" name="b" value="1"> <input type="radio" name="b" value="2"> <input type="radio" name="b" value="3"> <input type="radio" name="b" value="4"> and so on.. If I click radio button A with value 2, I want to output the total at the bottom as "2".. Also, if I click radio button B with value 3, I want to output the total of A and B as 5 and so on.. How can I automatically calculate the answer based on which radio button was click? update: I got my answer from this site: http://stackoverflow.com/questions/1...s-using-jquery Dear All, I am trying to design a from with radio buttons and text boxes which will accept text values upon clicking the radio buttons. So basically the textbox only appears when the radio button is clicked. The problem I am facing is the textbox does not hide upon selecting different radio button. Below I am posting the javascript and the associated html form for the same. I would like to request some suggestions and directions for the same. Regards Code: Javascript: <script type="text/javascript"> function show() { var i = 0; var el; while(el = document.getElementsByName('radio')[i++] ) { (document.getElementById('radio'+i).checked) ? document.getElementById('text'+i).style.display="block" : document.getElementById('text'+i).style.display="none" } } </script> Code: <div id="SeqInput"> <form method="post" action="the url to process this form" > <div> <label><input type="radio" name="seqinput" value="accession" id="radio1" onclick="show()"></label> NCBI accession number: <label for="accession"><input type="text" id="text1"></label><br> <label><input type="radio" name="seqinput" value="gene" id="radio2" onclick="show()"></label> NCBI Gene Name: <label for="gene"> <input type="text" id="text2"></label><br> <label><input type="radio" name="seqinput" value="file" id="radio3"></label> Upload fasta sequence from file: <label for="file"><input type="file" id="file"></label><br> <label><input type="radio" name="seqinput" value="fasta" id="radio4" onclick="show()"></label> Click to type in or copy/paste the fasta sequence:<br> <label><textarea rows="10" cols="100" id="text3" style="display: none"> </textarea></label> </div> </form> </div> Hi, I have a choice of three market items and I want the value of the selected one to be sent to my form. My code is: Code: <script type="text/javascript"> function loadXMLDoc2(File,ID,Msg){ if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else { try{ xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } } xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ document.getElementById(ID).innerHTML=xmlhttp.responseText; } } var params=Msg; xmlhttp.open("POST",File,true); xmlhttp.setRequestHeader("Pragma", "Cache-Control:no-cache"); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.setRequestHeader("Content-length", params.length); xmlhttp.setRequestHeader("Connection", "close"); xmlhttp.send(params); } </script> </head> <body> <input type="radio" name="myitem" id="myitem" value="All;" onclick="OtherFunction()" />All <br /><br />' <input type="radio" name="myitem" id="myitem" value="Shirts" onclick="OtherFunction()" />Shirts <br /><br /> <input type="radio" name="myitem" id="myitem" value="Trousers" onclick="OtherFunction()" />Trousers <br /><br /> <br /><br /> <input type="button" class="indent" name="submitB" id="submitB" value="Submit" onclick="loadXMLDoc2('insertMarket.php','txtHint', 'md='+encodeURI(document.getElementById('myitem').value))" /> <div id="txtHint"></div> This doesn't work. I have tried giving them different ids, I have tried replacing the id with checked="id=\'myitem\'", I have tried getElementById(\'myitem.checked\'), I have tried getElementbyName. In my full page I have far more radio buttons, so I don't want to do a getElementById(\'myitem[0].checked || myitem[1].checked etc. I think the solution must be along these lines. But I have run out of alternatives to try. Needless to say as it currently stands it gives the last radio button's value, which means it doesn't like them having the same id, but when I tried changing how the id was applied, or called - ElementByName, FF gives the error message as id is null. Here's my HTML: Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> <title>The Happy Hoppin' Hotel</title> <script src="happyhoppin.js" language="javascript" type="text/javascript"></script> </head> <body> <h1>The Happy Hoppin' Hotel Checkout Page</h1> <h2>Fill out the form below to calculate balance due</h2> <form> Guest ID Number: <input type="text" id="guestID" /> <br /> <br /> Room Type: <select id="roomType"> <option></option> <option>Parlor</option> <option>Single</option> <option>Double</option> </select> <br /> <br /> Length of Stay: <input type="text" id="stayLength" /> <br /> <br /> Number of Drinks: <input type="text" id="drinkNumber" /> <br /> <br /> Number of Towels: <input type="text" id="towelNumber" /> <br /> <br /> Number of Flushes: <input type="text" id="flushNumber" /> <br /> <br /> Bug Complaints?: <br /> <form name="bugComplaintRadio"> <input type="radio" name="bugComplaint" value="No" />No</label> <br /> <input type="radio" name="bugComplaint" value="Yes" />Yes</label> <br /> </form> <br /> Customer Comments: <br /> <textarea name="customerComment" cols="50" rows="5">Enter your comments here...</textarea> <br /> <br /> <input type="button" onclick="calculateBill()" value="Calculate Bill"> </form> </body> </html> Here's my Javascript: Code: const parlorPrice = 80; const singlePrice = 100; const doublePrice = 150; const drinkPrice = 5; const towelPrice = 3; const flushPrice = 1; var guestID = 0; var roomPrice = 0; var stayLength = 0; var drinkNumber = 0; var towelNumber = 0; var flushNumber = 0; var totalDue = 0; var totalCharge = 0; function calculateBill(){ validateForm(); //roomType// if(roomType == "Parlor"){ roomPrice = parlorPrice; } if(roomType == "Single"){ roomPrice = singlePrice; } if(roomType == "Double"){ roomPrice = doublePrice; } //roomType// //drinkCharge// drinkCharge = drinkNumber * drinkPrice; //drinkCharge// //towelCharge// towelCharge = towelNumber * towelPrice; //towelCharge// //flushCharge// flushCharge = flushNumber * flushPrice; //flushCharge// //totalCharge// totalCharge = roomPrice + drinkCharge + towelCharge + flushCharge; //totalCharge// //**bugDiscount**// function getCheckedRadio() { bugValue = ""; bugLength = document.bugComplaintRadio.bugComplaint.length; var bugDiscount = 0; for (x = 0; x < bugLength; x ++) { if (document.bugComplaintRadio.bugComplaint[x].checked) { bugValue = document.bugComplaintRadio.bugComplaint[x].value; } } if (bugValue == "") { alert("You did not choose whether you had a bug complaint or not"); } if (bugValue = "No"){ bugDiscount = 0; } if (bugValue = "Yes"){ bugDiscount = 20; } } //**bugDiscount**// getCheckedRadio(); //totalDue// totalDue = totalCharge + bugDiscount //totalDue// displayBill(); } function validateForm(){ //guestID// guestID = parseInt(document.getElementById("guestID").value); if(isNaN(guestID)){ alert("Guest ID must be a number"); return; } if(guestID <= 0){ alert("Guest ID must be greater than zero"); return; } //guestID// //roomType// roomType = document.getElementById("roomType").value; if(roomType == ""){ alert("Room type must be selected"); return; } //roomType// //stayLength// stayLength = parseInt(document.getElementById("stayLength").value); if(isNaN(stayLength)){ alert("Length of stay must be a number"); return; } if(stayLength <= 0){ alert("Length of stay must be greater than zero"); return; } //stayLength// //drinkNumber// drinkNumber = parseInt(document.getElementById("drinkNumber").value); if(isNaN(drinkNumber)){ alert("Number of drinks must be a number"); return; } if(drinkNumber <= 0){ alert("Number of drinks must be greater than zero"); return; } if(drinkNumber > 25){ alert("Number of drinks has exceeded 25"); return; } //drinkNumber// //towelNumber// towelNumber = parseInt(document.getElementById("towelNumber").value); if(isNaN(towelNumber)){ alert("Number of towels must be a number"); return; } if(towelNumber <= 0){ alert("Number of towels must be greater than zero"); return; } //towelNumber// //flushNumber// flushNumber = parseInt(document.getElementById("flushNumber").value); if(isNaN(flushNumber)){ alert("Number of flushes must be a number"); return; } if(flushNumber <= 0){ alert("Number of flushes must be greater than zero"); return; } //flushNumber// //customerComment// customerComment = document.getElementById("customerComment"); //customerComment// } function displayBill(){ var newPage = "<html><head><title>Billing Summary</title></head>"; newPage += "<body><h1>Happy Hoppin Hotel</h1>"; newPage += "<h2>Guest Billing Statement</h2>"; newPage += "Guest Identification: #" + guestID; newPage += "<br />"; newPage += "Room Type: " + roomType; newPage += "<br />"; newPage += "Room Charge: $" + roomPrice; newPage += "<br />"; newPage += "Length of Stay: " + stayLength + " days"; newPage += "<br />"; newPage += "Drink Charge: $" + drinkCharge; newPage += "<br />"; newPage += "Towel Charge: $" + towelCharge; newPage += "<br />"; newPage += "Flushing Charge: $" + flushCharge; newPage += "<br />"; newPage += "Total Charge: $" + totalCharge; newPage += "<br />"; newPage += "Discount: $" + bugDiscount; newPage += "<br />"; newPage += "Total Due: $" + totalDue; newPage += "<br />"; newPage += "<h3>Come back and visit us again at the Happy Hoppin' Hotel!</h3>"; var z = window.open("","","width=400,height=500"); z.document.write(newPage); z.document.close(); } My question is, I've been spending countless hours trying to: 1. Make two radio buttons indicating "No" and "Yes", 2. Retrieve which selection the user has made, 3. Change the value of "bugDiscount" or the amount of money ($20 or $0) depending on which choice the user made; $0 for No & $20 for Yes. 4. Subtract the value of bugDiscount (0 or 20) from the totalCharge to get TotalDue I know I'm close, but I've tried any number of variations in my code and I still can't seem to get it right. Can anyone help? Hello all I created a form which has a lot of textboxes, checkboxes and select-lists which are getting filled up by the records from a database table. I am basically creating an edit screen for a record. No I want to check all these input elements using javascript validation. I want this to performed when a button "Archive" is pressed. My problem is this "Archive button" needs to be a submit button. This does run the javascript validation but after completing the validation it submits the form. I want that submission should be stopped when the validation is violated. how can I do this? What I want is a button which acts as a default button (triggers the onclick event when I press enter) but submits only if the form is valid. 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? 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> |