JavaScript - 2 Select Boxes In 1 Form With Onchange Display
I'm using onchange display to hide/show form elements depending on the value of a select box. It works perfectly well (I actually really adore it) for one select box, but I have another select box which I'd like to act similarly.
Code: <head> <script type="text/javascript"> // <![CDATA[ function display(obj,id1,id2,id3,id4) { txt = obj.options[obj.selectedIndex].value; document.getElementById(id1).style.display = 'none'; document.getElementById(id2).style.display = 'none'; document.getElementById(id3).style.display = 'none'; document.getElementById(id4).style.display = 'none'; if ( txt.match(id1) ) { document.getElementById(id1).style.display = 'block'; } if ( txt.match(id2) ) { document.getElementById(id2).style.display = 'block'; } if ( txt.match(id3) ) { document.getElementById(id3).style.display = 'block'; } if ( txt.match(id4) ) { document.getElementById(id4).style.display = 'block'; } } // ]]> </script> </head><body> <form action="#"> <select name="Stype" onchange="display(this,'oneshot','outtake','multi','chapter');"> <option>Please select:</option> <option value="oneshot">Oneshot</option> <option value="outtake">Outtake</option> <option value="multi">Original Multi-Chapter</option> <option value="drabbles">Drabbles</option> <option value="outline">Outline Preview</option> <option value="chapter">Chapter Preview</option> </select><BR><BR> <div id="oneshot" style="display: none;">Some fields here</div> <div id="outtake" style="display: none;">Some different fields here</div> <div id="multi" style="display: none;">Some other fields here</div> <div id="chapter" style="display: none;">Some more fields here</div> </form> </body> But when I go to add a second select (obj,id1,id2,id3,id4,id5,id6) with new "ifs" and id's, etc and so forth, neither work. Code: <head> <script type="text/javascript"> // <![CDATA[ function display(obj,id1,id2,id3,id4,id5,id6) { txt = obj.options[obj.selectedIndex].value; document.getElementById(id1).style.display = 'none'; document.getElementById(id2).style.display = 'none'; document.getElementById(id3).style.display = 'none'; document.getElementById(id4).style.display = 'none'; document.getElementById(id5).style.display = 'none'; document.getElementById(id6).style.display = 'none'; if ( txt.match(id1) ) { document.getElementById(id1).style.display = 'block'; } if ( txt.match(id2) ) { document.getElementById(id2).style.display = 'block'; } if ( txt.match(id3) ) { document.getElementById(id3).style.display = 'block'; } if ( txt.match(id4) ) { document.getElementById(id4).style.display = 'block'; } if ( txt.match(id5) ) { document.getElementById(id5).style.display = 'block'; } if ( txt.match(id6) ) { document.getElementById(id6).style.display = 'block'; } } // ]]> </script> </head><body> <form action="#"> <select name="Stype" onchange="display(this,'oneshot','outtake','multi','chapter');"> <option>Please select:</option> <option value="oneshot">Oneshot</option> <option value="outtake">Outtake</option> <option value="multi">Original Multi-Chapter</option> <option value="drabbles">Drabbles</option> <option value="outline">Outline Preview</option> <option value="chapter">Chapter Preview</option> </select><BR><BR> <div id="oneshot" style="display: none;">Some fields here</div> <div id="outtake" style="display: none;">Some different fields here</div> <div id="multi" style="display: none;">Some other fields here</div> <div id="chapter" style="display: none;">Some more fields here</div> <BR><BR><BR> <select name="Atype" onchange="display(this,'romance','adventure');"> <option>Please select:</option> <option value="romance">Romance</option> <option value="adventure">Adventure</option> </select><BR><BR> <div id="romance" style="display: none;">Some new fields here</div> <div id="adventure" style="display: none;">Some even newer fields here</div> </form> </body> Is there any way to fuse them and get a second select to work the same? Thanks in advance for the help! Similar TutorialsHello, I am working on a CGI/Ajax application to interface with a database. I have the back-end Perl/CGI application working, so now it it is time to design the web interface and respective forms. So here goes, I am attempting to create dynamic list boxes, but I am unable to pass a value to the 'onChange' event. Here is my code (this is a proof of concept and highly stripped down): Code: <html> <head> </head> <body> <SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript"> var array = [ 'name', 'age', 'year']; function init(sel_val){ for (var i = 0; i < array.length; i++){ document.write(i + " " + array[i] + "<br />"); } for (var i = 0; i< array.length; i++){ document.product.id_type.options[i] = new Option(i + array[i], i); } } function OnChange(sel_val) { // for(i = document.product.id_style.length - 1; i > 0; i--) // document.product.id_style.options[i] = null; // document.product.id_style.options[0] = new Option("something else", 15); alert("pressed" + " " + sel_val + "<br />"); } </script> <form name="product"> <select name="id_type" size="5" style="width: 150px;" onChange="OnChange()"></select> <select name="id_style" size="5" style="width: 150px;" ></select> </form> <script> init(); </script> </body> </html> I'm well versed in Perl and Java but I am a JavaScript newbie, so go easy. I understand that sel_val is not being set, but I'm not sure how it should (or could) be set. I would like to use a hash instead of integer values for `i` document.product.id_type.options[i] = new Option(i + array[i], i); becomes document.product.id_type.options[i] = new Option(hash[key], key); Any thoughts, comments, criticisms, jokes are welcome. Thanks in advance for the assist. All, If I have the following code: Code: <form name="datatoshow" id="datatoshow"> Want to learn more about the sie? Use the drop down menu:<br /> <select name="thingtoshow" onchange="javascript:showvalues(this.datatoshow);"> <option value="home">Home</option> <option value="help">Help!</option> <option value="refer">Refer a Friend</option> </select> </form> This doesn't do anything on the onchange. The code it's supposed to send to is: Code: function showvalues(selObj){ alert("it gets here"); var valuetoshow; valuetoshow = "valuetoshow="+selObj.options[selObj.selectedIndex].value; alert(valuetoshow); makePOSTRequest('showhome.php', valuetoshow); } This is in external js file. For some reason it doesn't send it and the alert never gets triggered. Thanks. Hi, Can anyone help with my Error. Just to give an idea on my objective. I have an user level that a user can choose between "User","Support" and "Admin" Level. If the user choose "Admin" my <div id='userlevel'> will become hidden and vise versa of the level. I have tested it on Html and js code it work just fine, but my error begun upon inserting it on php. My error on my page said " 'selectmenu' is null or not an object". Can anyone help me with this i'm really desperate on this. Thanks. This is my html and js code Code: <html> <head> <form > <select id="mymenu" size="1" > <option value="nothing">Select a site</option> <option value="User">User</option> <option value="Support">Support</option> <option value="Admin">Admin</option> </select> <div id="level"> <table border=1> <tr> <td>Sample</td> </tr> </table> </div> </form> <script type="text/javascript"> var selectmenu=document.getElementById("mymenu") selectmenu.onchange=function(){ //run some code when "onchange" event fires var chosenoption=this.options[this.selectedIndex] //this refers to "selectmenu" if (chosenoption.value=="Admin"){ //alert('Did I mention I had a guestbook? Well SIGN IT!'); //open target site (based on option's value attr) in new window document.getElementById('level').style.visibility = 'hidden'; }else if(chosenoption.value=="Support"){ document.getElementById('level').style.visibility = 'visible'; }else if(chosenoption.value=="User"){ document.getElementById('level').style.visibility = 'visible'; } } </script> </html> My viewsource 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"> <head> <title>Edit User</title> <link href="css/mystyle.css" rel="stylesheet" type="text/css"/> <script src="jquery\jquery.min.js"></script> <script type="text/javascript" src="jquery\jquery.validate.js"></script> <script> $(document).ready(function(){ $.validator.addMethod("noSpecialChars", function(value, element) { return this.optional(element) || /^[a-z0-9\_]+$/i.test(value); }, "<font size='3' color='#FF0000'>Username must contain only letters, numbers, or underscore.</font>"); $("#edit").validate({ rules: { pass: "required", rpass: { equalTo: "#pass" }, fname:"required", lname:"required", email:"required email", dept:"required", userlvl:"required" } }); }); </script> <script type="text/javascript"> var selectmenu=document.getElementById("ulvl") selectmenu.onchange=function(){ //run some code when "onchange" event fires var chosenoption=this.options[this.selectedIndex] //this refers to "selectmenu" if (chosenoption.value=="Admin"){ document.getElementById('userlevel').style.visibility = 'hidden'; }else if(chosenoption.value=="Support"){ document.getElementById('userlevel').style.visibility = 'visible'; }else if(chosenoption.value=="User"){ document.getElementById('userlevel').style.visibility = 'visible'; } } </script> <style type="text/css"> body { font-family: arial; /* you need some backups here */ font-size: 17px; } </style> </head> <body> <br/> <br/> <p> <table BORDERCOLOR="#0B0B0B" border='1' bgcolor="#F5F5FA" width="70%" align='center' > <tr> <td width="100%" align="left" valign="middle"> <img src='img/editprofile.png'> </td> </tr> <tr> <td width="100%" align='center' > <table> <form method='post' id='edit' name='edit' action='edituser.php?UserName=Alphee' onSubmit="javascript: var x=window.confirm('Do you wan\'t to save this User?');if (!x) return(false);"> <tr> <input type='hidden' value=Alphee name='uname'> <td align='right'><b>User Name:</b></td> <td align='left'>Alphee</td> </tr> <tr> <td align='right'><b>First Name:</b></td> <td align='left'><input type='text' id='fname' value='Alphee' name='fname'></td> </tr> <tr> <td align='right'><b>Last Name:</b></td> <td align='left'><input type='text' id='lname' value='Saspa' name='lname'></td> </tr> <tr> <td align='right'><b>Email Address:</b></td> <td align='left'><input type='text' size='35' id='email' value='myemail.com' name='email'></td> </tr> <tr> <td align='right'><b>Department:</b></td> <td align='left'> <select name='dept' tabindex='8'><option >MIS</option><option >Acct</option><option >HR</option></select> </td> </tr> <tr> <td align='right'><b>User Level:</b></td> <td align='left'> <select class='ulvl' id='ulvl' name='ulvl' tabindex='9' ><option Selected=Selected>User</option><option value='User'>User</option><option value='Support'>Support</option><option value='Admin'>Admin</option></select></td></tr></table><div class='userlevel' id='userlevel'><tr><td align='center'><b>User Access</b></td></tr><tr><td><input type='checkbox' name='CreateTicket'>Create Ticket<br><input type='checkbox' name='AddUser' >Add User<br><input type='checkbox' name='EditProfile' >Edit/Delete User<br><input type='checkbox' name='ResetPass'>Reset Password<br><input type='checkbox' name='Department'>Add Department<br><input type='checkbox' name='Category'>Add Category<br><input type='checkbox' name='SubCategory'unchecked>Add Sub-Category</td></tr></div> <tr> <td align='center' > <input type='submit' value='Save' name='save' title='Save User'> </td> </tr> </form> </td> </tr> </table> </body> </html> My actual code with js and php PHP Code: <?php session_start(); if(isset( $_SESSION['username'])){ include_once("conn.php"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Edit User</title> <link href="css/mystyle.css" rel="stylesheet" type="text/css"/> <script src="jquery\jquery.min.js"></script> <script type="text/javascript" src="jquery\jquery.validate.js"></script> <script> $(document).ready(function(){ $.validator.addMethod("noSpecialChars", function(value, element) { return this.optional(element) || /^[a-z0-9\_]+$/i.test(value); }, "<font size='3' color='#FF0000'>Username must contain only letters, numbers, or underscore.</font>"); $("#edit").validate({ rules: { pass: "required", rpass: { equalTo: "#pass" }, fname:"required", lname:"required", email:"required email", dept:"required", userlvl:"required" } }); }); </script> <script type="text/javascript"> var selectmenu=document.getElementById("ulvl") selectmenu.onchange=function(){ //run some code when "onchange" event fires var chosenoption=this.options[this.selectedIndex] //this refers to "selectmenu" if (chosenoption.value=="Admin"){ document.getElementById('userlevel').style.visibility = 'hidden'; }else if(chosenoption.value=="Support"){ document.getElementById('userlevel').style.visibility = 'visible'; }else if(chosenoption.value=="User"){ document.getElementById('userlevel').style.visibility = 'visible'; } } </script> <style type="text/css"> body { font-family: arial; /* you need some backups here */ font-size: 17px; } </style> </head> <body> <br/> <br/> <p> <table BORDERCOLOR="#0B0B0B" border='1' bgcolor="#F5F5FA" width="70%" align='center' > <tr> <td width="100%" align="left" valign="middle"> <img src='img/editprofile.png'> </td> </tr> <tr> <td width="100%" align='center' > <?php if(isset($_POST['save'])){ //User Access if(isset($_POST['CreateTicket'])){ $CreateTicket='1'; }else{ $CreateTicket='0'; } if(isset($_POST['AddUser'])){ $AddUser='1'; }else{ $AddUser='0'; } if(isset($_POST['Department'])){ $Department='1'; }else{ $Department='0'; } if(isset($_POST['Category'])){ $Category='1'; }else{ $Category='0'; } if(isset($_POST['SubCategory'])){ $SubCategory='1'; }else{ $SubCategory='0'; } if(isset($_POST['EditProfile'])){ $UserEdit='1'; }else{ $UserEdit='0'; } if(isset($_POST['ResetPass'])){ $PassReset='1'; }else{ $PassReset='0'; } mssql_query("sp_edituser @lname='$_POST[lname]',@fname='$_POST[fname]',@upby='$_SESSION[username]',@uname='$_POST[uname]',@userlevel='$_POST[ulvl]',@email='$_POST[email]',@department='$_POST[dept]',@Cticket='$CreateTicket',@AddUser='$AddUser',@adept='$Department',@acat='$Category',@asubcat='$SubCategory',@edituser='$UserEdit',@pass='$PassReset'"); mssql_close($con); echo "<b><p align='center'><font color='#F0000' size='3'>User has been edit.</font></p></b>"; } $d=mssql_query("Select * from vw_dept"); $lvl=mssql_query("spvw_userlevel @username='$_GET[UserName]' "); //$lvl=mssql_query("Select UserLevel from tblUser where UserName='$_GET[UserName]'"); $row=mssql_fetch_array(mssql_query("spview_edituser @username='$_GET[UserName]'")); //print "<meta http-equiv='refresh' content='=2;Viewuser.php'/>"; ?> <table> <form method='post' id='edit' name='edit' action='edituser.php?UserName=<?php echo $row['UserName'];?>' onSubmit="javascript: var x=window.confirm('Do you wan\'t to save this User?');if (!x) return(false);"> <tr> <input type='hidden' value=<?php echo $row['UserName'];?> name='uname'> <td align='right'><b>User Name:</b></td> <td align='left'><?php echo $row['UserName'];?></td> </tr> <tr> <td align='right'><b>First Name:</b></td> <td align='left'><input type='text' id='fname' value='<?php echo $row['Firstname'];?>' name='fname'></td> </tr> <tr> <td align='right'><b>Last Name:</b></td> <td align='left'><input type='text' id='lname' value='<?php echo $row['Lastname'];?>' name='lname'></td> </tr> <tr> <td align='right'><b>Email Address:</b></td> <td align='left'><input type='text' size='35' id='email' value='<?php echo $row['Email'];?>' name='email'></td> </tr> <tr> <td align='right'><b>Department:</b></td> <td align='left'> <?php echo "<select name='dept' tabindex='8'>"; while($dept=mssql_fetch_array($d)){ echo "<option "; if ($row['dept']==$dept['DeptName']) echo "Selected=Selected"; echo ">".$dept['DeptName']."</option>"; } echo '</select>'; ?> </td> </tr> <tr> <td align='right'><b>User Level:</b></td> <td align='left'> <?php echo "<select class='ulvl' id='ulvl' name='ulvl' tabindex='9' >"; while($level=mssql_fetch_array($lvl)){ echo "<option "; if ($row['UserLevel']==$level['UserLevel']) echo "Selected=Selected"; echo ">".$level['UserLevel']."</option>"; } echo "<option value='User'>User</option>"; echo "<option value='Support'>Support</option>"; echo "<option value='Admin'>Admin</option>"; echo '</select>'; echo "</td>"; echo "</tr>"; echo "</table>"; if($UserAccess=mssql_fetch_array(mssql_query("sp_useraccess @username='$_GET[UserName]',@userlevel='Admin'"))){ echo "<div class='userlevel' id='userlevel'>"; echo "<tr>"; echo "<td align='center'>"; echo "<b>User Access</b>"; echo "</td>"; echo "</tr>"; echo "<tr>"; echo "<td>"; echo"<input type='checkbox' name='CreateTicket'"; if(trim($UserAccess[CreateTicket])=='1'){echo 'checked';}echo ">Create Ticket<br>"; echo "<input type='checkbox' name='AddUser' "; if(trim($UserAccess[AddUser])=='1'){echo 'checked';}echo">Add User<br>"; echo "<input type='checkbox' name='EditProfile' ";if(trim($UserAccess[AEditUser])=='1'){echo 'checked';}echo">Edit/Delete User<br>"; echo "<input type='checkbox' name='ResetPass'"; if(trim($UserAccess[APass])=='1'){echo 'checked';} echo">Reset Password<br>"; echo "<input type='checkbox' name='Department'"; if(trim($UserAccess[ADept])=='1'){echo 'checked';} echo">Add Department<br>"; echo "<input type='checkbox' name='Category'"; if(trim($UserAccess[ACat])=='1'){echo 'checked';}echo">Add Category<br>"; echo "<input type='checkbox' name='SubCategory'"; if(trim($UserAccess[ASubCat])=='1'){echo 'checked';}else{ echo 'unchecked';}echo">Add Sub-Category"; echo "</td>"; echo "</tr>"; echo "</div>"; } ?> <tr> <td align='center' > <input type='submit' value='Save' name='save' title='Save User'> </td> </tr> </form> </td> </tr> </table> </body> </html> <?php }else{ //not logged in header('location: login.php'); } ?> I am trying to add an onchange event to a select tag. This is my code, but it does not appear to be working. Any advice is appreciated. Thanks... Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=windows-1250"> <meta name="generator" content="PSPad editor, www.pspad.com"> <title></title> <script type="text/javascript"> function myLoad () { var mySelect = document.getElementsByName('test'); mySelect.onchange = function(){alert('hi')}; } </script> </head> <body onLoad="myLoad()"> <select name="test" > <option value="1">1</option> <option value="2">2</option> </select> </body> </html> Hello everyone. I learned javascript mainly from reading code. I'm have the most experience in c++. At any rate, what I want to happen is this User chooses an option from a dropdown (select form.) A textbox outputs the option they selected. This is my code so far: don't laugh at my old school c++ mindset.. It's all I know Code: <script type="text/javascript"> function setcharge(chargeamount) { var d; switch (chargeamount) { case 0: var x="495.00"; return x; break; case 1: var x="350.00"; return x; break; case 2: var x="125.00"; return x; break; case 3: var x="250.00"; return x; break; case 4: var x="545.00"; return x; break; case 5: var x="545.00"; return x; break; case 6: var x="50.00"; return x; break; case 7: var x="189.00"; return x; break; case 8: var x="225.00"; return x; break; } document.writeln("Current Total: "); document.writeln(x); break; } </script> <script type="text/javascript"><!-- document.pfit.chargetype.onchange=(var x=setcharge(document.pfit.getElementById("chargetype").selectedindex)); document.writeln("I agree to pay: "); document.writeln(x); // --></script> The form code is Code: <p><label>Select Course Type <select name="chargetype" id="chargetype"> <option value="aCourseOnly">$495.00 - a Course Only</option> <option value="bCousreOnly">$350.00 - b Course Only</option> <option value="aExamOnly">$125.00 - a Exam Only</option> <option value="bExamOnly">$250.00 - a Exam Only</option> <option value="aValueOption">$545.00 -a Course and Exam</option> <option value="bValueOption">$545.00 - a Course and Exam</option> <option value="CECIndividual">Continuing Education Credit (CEC) Course Individual Session Fee - $50.00 Each 4 hour Session</option> <option value="CEC2Day">2 Day a Continuing Educaton Credit(CEC) Course Review $189.00</option> <option value="CEC3Day">3 Day a Continuing Educaton Credit(CEC) Course Review $225.00</option></select> </label>(Complimentary with course)</p> I have a feeling I'm using the DOM wrong, but then, I am a noob at javascript. Please help me. I have a multiple fields on my page and wish to have a reusable javascript to update the previous box with the selction made. how would this be done Code: <form name="form1" method="post" action=""> <p> <input type="textone" name="textfieldone" id="textfieldone"> </p> <p> <select name="selectone" onChange="UpdatePreviousField()"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> </p> <p> </p> <p> </p> <p> </p> <p> </p> <p> <input type="texttwo" name="textfieldtwo" id="textfieldtwo"> </p> <p> <select name="selecttwo" onChange="UpdatePreviousField()"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> </p> <p> </p> </form> Trying to get the divs to switch style properties when selected form select menu. Any help would be great! Code: <script type="text/javascript"> function showstuff(element){ if(document.getElementById(element).style.display = 'block') { document.getElementById(have).style.visibility="block"; document.getElementById(look).style.visibility="none"; } else if(document.getElementById(element).style.visibility = 'block') { document.getElementById(look).style.visibility="block"; document.getElementById(have).style.visibility="none"; } } </script> <select name="type" onchange="showstuff(this.value);"> <option value="look">Look</option> <option value="have">Have</option> </select> <div id="have" style="display:block;">Have</div> <div id="look" style="display:none;">Look</div> Hi, I am effectively using this script to grab elements based on a select from the db: http://www.w3schools.com/PHP/php_ajax_database.asp My question is, how can I, instead of changing what's present on the page, change the display value to "none", so the elements that are being gathered can be re-submitted to the form? Thanks Code: <script type="text/javascript"> function showUser(str) { if (str=="") { document.getElementById("txtHint").innerHTML=""; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("txtHint").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","getuser.php?q="+str,true); xmlhttp.send(); } </script> Calculating quiz answers? Code: var correctAnswers = new Array(); correctAnswers[1] = "Extensible Hypertext Markup Language"; correctAnswers[2] = "<p></p>"; correctAnswers[3] = "<br />"; function checkAnswers(){ var score = 0; for (i=1; i<4; i++){ correctAnswers = getSelectValue("quiz","q" + i); if (correctAnswers == correctAnswers[i]){ score++; } } I have the below JS code to change up a select box based on what is selected in another select box. IE9 broke this somehow. It still works in other browsers as well as IE8 and IE7. When you select something in select box A, it properly populates select box B. However when you go back and change select box A again the script stops working completely. The error I'm getting from the IE9 developer tools debugger is: SCRIPT65535: Invalid calling object dynamicselect.js, line 31 character 18 I have bolded the relevant line below. Code: function dynamicSelect(id1, id2) { // Browser and feature tests to see if there is enough W3C DOM support var agt = navigator.userAgent.toLowerCase(); var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1)); var is_mac = (agt.indexOf("mac") != -1); if (!(is_ie && is_mac) && document.getElementById && document.getElementsByTagName) { // Obtain references to both select boxes var sel1 = document.getElementById(id1); var sel2 = document.getElementById(id2); // Clone the dynamic select box var clone = sel2.cloneNode(true); // Obtain references to all cloned options var clonedOptions = clone.getElementsByTagName("option"); // Onload init: call a generic function to display the related options in the dynamic select box refreshDynamicSelectOptions(sel1, sel2, clonedOptions); // Onchange of the main select box: call a generic function to display the related options in the dynamic select box sel1.onchange = function() { refreshDynamicSelectOptions(sel1, sel2, clonedOptions); }; } } function refreshDynamicSelectOptions(sel1, sel2, clonedOptions) { // Delete all options of the dynamic select box while (sel2.options.length) { sel2.remove(0); } // Create regular expression objects for "select" and the value of the selected option of the main select box as class names var pattern1 = /( |^)(select)( |$)/; var pattern2 = new RegExp("( |^)(" + sel1.options[sel1.selectedIndex].value + ")( |$)"); // Iterate through all cloned options for (var i = 0; i < clonedOptions.length; i++) { // If the classname of a cloned option either equals "select" or equals the value of the selected option of the main select box if (clonedOptions[i].className.match(pattern1) || clonedOptions[i].className.match(pattern2)) { // Clone the option from the hidden option pool and append it to the dynamic select box sel2.appendChild(clonedOptions[i].cloneNode(true)); } } } Thank you in advance for any help provided. I'm trying to do this using numerical arrays for an assignment: Create a webpage with three select boxes. If basketball is selected in the first select box, the second select box should display the names Celtics, Lakers, and Bulls. If Celtics is selected from the second select box, the third select box should display the names Larry Bird, Bill Russell, and Kevin McHale. I think i have a good start but i can't seem to get the fields to automatically populate with the players. This has to be done solely with JavaScript. Any help would be greatly appreciated? <html> <head> <script type="text/javascript"> <!-- var teams = new Array() teams[1] = new Array() teams[1][0] = "Celtics" teams[1][1] = "Lakers" teams[1][2] = "Bulls" teams[2] = new Array() teams[2][0] = "Yankees" teams[2][1] = "Cardinals" teams[2][2] = "Reds" var basketball = new Array() basketball[0] = new Array() basketball[0][0] = "Larry Bird" basketball[0][1] = "Bill Russell" basketball[0][2] = "Kevin McHale" basketball[1] = new Array() basketball[1][0] = "Wilt Chamberlain" basketball[1][1] = "Jerry West" basketball[1][2] = "Magic Johnson" basketball[2] = new Array() basketball[2][0] = "Micheal Jordan" basketball[2][1] = "Scottie Pippen" basketball[2][2] = "Dennis Rodman" var baseball = new Array() baseball[0] = new Array() baseball[0][0] = "Babe Ruth" baseball[0][1] = "Joe DiMaggio" baseball[0][2] = "Mickey Mantle" baseball[1] = new Array() baseball[1][0] = "Mark McGuire" baseball[1][1] = "Ozzie Smith" baseball[1][2] = "Willie McGee" baseball[2] = new Array() baseball[2][0] = "Pete Rose" baseball[2][1] = "Johnny Bench" baseball[2][2] = "Joe Morgan" function fillTeams() { var whichIndex = document.getElementById("theSport").selectedIndex var numberOfTeams = teams[whichIndex].length for(i=0;i < numberOfTeams; i++){ document.getElementById("theTeams").options[i].text = teams[whichIndex][i] } } function fillPlayers() { var whichIndex = document.getElementById("theTeams").selectedIndex if(document.getElementById("theTeams").selectedIndex=="basketball") var numberOfPlayers = teams[teams[whichIndex]].length for(i=0;i < numberOfPlayers; i++) { document.getElementById("thePlayers").options[i].text = basketball[teams[whichIndex]][i] } else if(document.getElementById("theTeams").selectedIndex =="baseball") for(i=0;i < numberOfPlayers; i++) { document.getElementById("thePlayers").options[i].text = basketball[teams[whichIndex]][i] } } //--> </script> </head> <body> <form> <select id="theSport" onChange="fillTeams()"> <option>Choose a Sport</option> <option>Basketball</option> <option> Baseball </option> </select> <select id="theTeams" onChange="fillPlayers()"> <option>................</option> <option></option> <option></option> </select> <select id="thePlayers" size="3"> <option> ...............</option> <option></option> <option></option> </select> </form> </body> </html> Hi all, I'm trying to customize a script I found. It's about two select boxes, one for continent selection and one for country selection. When user selects a continent from the first select box, the second select box is filled with the list of the proper countries that belong to this continent. You can see that code of the script he http://www.howtocreate.co.uk/jslibs/htmlhigh/countryselect.html In my page, the continent select box is loaded with a continent-value already selected (the selection depends on a database value) and I want to have the second countries select box, also loaded with the proper countries. I cannot make this happen, unless I change the continent's selection and trigger the onchange event. Can I someway keep the onchange event and also add the ability to have a continent and it's list of countries already loaded? Hello to all and thank you for any help beforehand. I have an issue with the script below, Select the top dropdown and the second gets populated, this is a nice piece of script, the only problem is that when the information is posted and presented on the process page I click page back to the form to rectify some other field but the ajax resets so I have to select Country & City each time even if thease fields are correct. I know that back button as well as bookmark is a problem with ajax but i think there is a solution the only thing is I don't know how to apply it to this script. Source of the script: http://www.dhtmlgoodies.com/index.ht...chained_select Ajax file: http://www.dhtmlgoodies.com/AJAX/ajax.js test.html Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title></title> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <meta name="description" content="" /> <meta name="keywords" content="" /> <script type="text/javascript" src="ajax.js"></script> <script type="text/javascript"> var ajax = new Array(); function getCityList(sel) { var countryCode = sel.options[sel.selectedIndex].value; document.getElementById('dhtmlgoodies_city').options.length = 0; // Empty city select box if(countryCode.length>0){ var index = ajax.length; ajax[index] = new sack(); ajax[index].requestFile = 'getCities.php?countryCode='+countryCode; // Specifying which file to get ajax[index].onCompletion = function(){ createCities(index) }; // Specify function that will be executed after file has been found ajax[index].runAJAX(); // Execute AJAX function } } function createCities(index) { var obj = document.getElementById('dhtmlgoodies_city'); eval(ajax[index].response); // Executing the response from Ajax as Javascript code } function getSubCategoryList(sel) { var category = sel.options[sel.selectedIndex].value; document.getElementById('dhtmlgoodies_subcategory').options.length = 0; // Empty city select box if(category.length>0){ var index = ajax.length; ajax[index] = new sack(); ajax[index].requestFile = 'getSubCategories.php?category='+category; // Specifying which file to get ajax[index].onCompletion = function(){ createSubCategories(index) }; // Specify function that will be executed after file has been found ajax[index].runAJAX(); // Execute AJAX function } } function createSubCategories(index) { var obj = document.getElementById('dhtmlgoodies_subcategory'); eval(ajax[index].response); // Executing the response from Ajax as Javascript code } </script> </head> <body> <form action="" method="post"> <table> <tr> <td>Country: </td> <td><select id="dhtmlgoodies_country" name="dhtmlgoodies_country" onchange="getCityList(this)"> <option value="">Select a country</option> <option value="dk">Denmark</option> <option value="no">Norway</option> <option value="us">US</option> </select> </td> </tr> <tr> <td>City: </td> <td><select id="dhtmlgoodies_city" name="dhtmlgoodies_city"> </select> </td> </tr> </table> </form> </body> </html> Here's the content of getCities.php Code: <?php if(isset($_GET['countryCode'])){ switch($_GET['countryCode']){ case "no": echo "obj.options[obj.options.length] = new Option('Bergen','1');\n"; echo "obj.options[obj.options.length] = new Option('Haugesund','2');\n"; echo "obj.options[obj.options.length] = new Option('Oslo','3');\n"; echo "obj.options[obj.options.length] = new Option('Stavanger','4');\n"; break; case "dk": echo "obj.options[obj.options.length] = new Option('Aalborg','11');\n"; echo "obj.options[obj.options.length] = new Option('Copenhagen','12');\n"; echo "obj.options[obj.options.length] = new Option('Odense','13');\n"; break; case "us": echo "obj.options[obj.options.length] = new Option('Atlanta','21');\n"; echo "obj.options[obj.options.length] = new Option('Chicago','22');\n"; echo "obj.options[obj.options.length] = new Option('Denver','23');\n"; echo "obj.options[obj.options.length] = new Option('Los Angeles','24');\n"; echo "obj.options[obj.options.length] = new Option('New York','25');\n"; echo "obj.options[obj.options.length] = new Option('San Fransisco','26');\n"; echo "obj.options[obj.options.length] = new Option('Seattle','27');\n"; break; } } ?> Hello, I'm working on a project that involves extracting values from a series of select boxes and then working out the result. The select boxes contain the following: Code: <select name="select_Col1_Row1"> <option value="blue">Blue</option> <option value="green">Green</option> <option value="red>Red</option> </select> <select name="select_Col1_Row2"> <option value="blue" selected="selected">Blue</option> <option value="green">Green</option> <option value="red>Red</option> </select> <input type="text" name="RedSum"> <input type="text" name="BlueSum"> <input type="text" name="GreenSum"> </select> As you can see by my code, I'm early days at this and guessing the steps on the way. I tried using getElementsByTagName on the select and then on the option but had no luck with that. The code below does a wonderful job of returning blue for both select statements... Code: <script type="text/javascript"> function getElements() { var table = document.getElementById("x"); var x = table.getElementsByTagName("option"); for (var i = 0; i < x.length; i++) { var status = x[i].getAttribute("selected"); alert(status); if (status == "selected") { var statushcap = x[i].getAttribute("id"); var statusvalue =x[i].getAttribute("value"); if (statusvalue == "blue") { alert(statusvalue); } } } alert(x.length); } </script> If someone could suggest some way to map the select tag and then extract its option value to being the user selected value, I'd most appreciate it. I can probably do the rest of it. Can you extract additional information from the id of the option that is selected as I'd like to sum additional information from the user's choice. Best, John hi ! i would like to write the code for multiple text box select as shown in the link below: http://www.downloadplex.com/Mobile/I...ne_284120.html please see the screen shot 3 Hello ladies and gentlemen, I would like to use some event handling on a form, not something I have done before and looking for some assistance. Here is my code: Code: <select name="LocO"> <option value=""></option> <option value="O">Outside</option> <option value="I">Inside</option> </select> <select name="LocA"> <option value=""></option> <option value="A">A</option> <option value="B">B</option> <option value="C">C</option> <option value="D">D</option> <option value="E">E</option> <option value="F">F</option> <option value="G">G</option> <option value="H">H</option> <option value="I">I</option> <option value="J">J</option> <option value="K">K</option> </select> <select name="Loc1"> <option value=""></option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> So what I need to happen, is based on the selection of the first selection box, some of the options of the other selection boxes should not be available. If Outside is selected, everything in LocA should be available, but only up to 4 in Loc1... and if Inside is selected, only up to E should be available in LocA and everything should be available in Loc1. Is this possible? Would appreciate some help making some minor enhancements to a pet adoption form: http://pawsct.org/application.php Problem - Applicants don't read. They answer "No" to the "Agree to Shelter Visit" question, then fill out the looooong application, and get abusive when told that they're not eligible for adoption. They apply from Florida and ignore the warnings about the 90 mile limit. Text notes just don't make enough of an impact. I want to use OnChange to give an alert if someone does not answer "Yes" to agree to a shelter visit (i.e. popup "You must agree to a shelter visit to qualify for an adoption from PAWS") and perhaps a warning message (red text reminder about the 90 mile limit next to the drop-down box) if someone enters a state other than CT. Second problem - I'm a volunteer who doesn't know javascript and can't cobble together a SIMPLE, workable solution from other code samples. Any assistance that you can provide would be most welcome and appreciated. Note: we are planning a redesign of the web site and may do some more sophisticated form validation (e.g. check age, valid e-mail, valid phone) in the future. But for now, we're just looking to check a few key fields for answers that would immediately disqualify an applicant. Howdy. Have an asp.net form where the textboxes have had the onblur attribute added. Though VS2008 still barks it's an invalid attribute... However, my problem is primarily w/the txtFICODate field. When testing using 10/10/2009 in this field, the code displays the appropriate msg based on format param. However, on exiting the isValidDate function in debug mode, I see that the code does not stop at the txtFICODate html but moves to the txtDOBB isValidDate function. Here the param is MM/DD/YYYY and it loops back into the function but now displays a different format message. Previous code (ValidateFICODate(obj)) below also caused the same looping error. Debugging the same code with the txtDOBB field (10/10/56), I see it enter the function, display the appropriate message and exit. However, in debug, the code comes back to the function and then selects the field contents. Appreciate any suggestions/comments on how to fix problem so code stops at the txtFICODate field . Using xp Pro SP3, visual studio 2008 (c#). in the process of writing this, I searched other post here related to onblur + loop. So changed the event to onchange...and while the looping does not now occur, the focus just moves to the next field. Huh? Thanks, Rey Code: On page load code(if (!isPostBack)): txtFICODate.Attributes.Add("onblur", "isValidDate(this, 'MM/DD/YY');"); txtDOBB.Attributes.Add("onblur", "isValidDate(this, 'MM/DD/YYYY');"); txtDOBC.Attributes.Add("onblur", "isValidDate(this, 'MM/DD/YYYY');"); Code: <asp:TextBox ID="txtDOBB" runat="server" Font-Bold="true" Text="" Columns="10" TextMode="SingleLine" AutoPostBack="false" onblur="return isValidDate(this, 'MM/DD/YYYY');" Width="120px"></asp:TextBox> <asp:TextBox ID="txtDOBC" runat="server" Font-Bold="true" Text="" Columns="10" TextMode="SingleLine" AutoPostBack="false" onblur="return isValidDate(this, 'MM/DD/YYYY');" Width="120px"></asp:TextBox> <asp:TextBox ID="txtFICODate" runat="server" Font-Bold="true" AutoPostBack="false" onblur="return isValidDate(this, 'MM/DD/YY');" Text="" Columns="6" TextMode="SingleLine" Width="120px" ></asp:TextBox> Code: function isValidDate(ctrl, fmt) { // retrieved 9/11/09 // from http://www.dotnetspider.com/resources/20790-Validatin-date-MM-DD-YY-Format-using-javascript.aspx // modified to pass in format (mm/dd/yy, mm/dd/yyyy so msg is appropriate if incorrect // also removed - option for dates, i.e. 09-11 var dateStr = ctrl.value; var datePat; //var datePat = /^(\d{1,2})(\/)(\d{1,2})\2(\d{2}|\d{4})$/; if (fmt.toString().toUpperCase() == 'MM/DD/YY') { datePat = /^(\d{2})(\/)(\d{2})\2(\d{2})$/; } if (fmt.toString().toUpperCase() == 'MM/DD/YYYY') { datePat = /^(\d{2})(\/)(\d{2})\2(\d{4})$/; } var matchArray = dateStr.match(datePat); // is the format ok? if (matchArray == null) { if (fmt.toString().toUpperCase() == 'MM/DD/YY') { alert("Invalid date format.\n" + "Please enter the date in the MM/DD/YY format (example: 1/15/08).") ctrl.focus(); ctrl.select(); return false; } if (fmt.toString().toUpperCase() == 'MM/DD/YYYY') { alert("Invalid date format.\n" + "Please enter the date in the MM/DD/YYYY format (example: 1/15/2008).") ctrl.focus(); ctrl.select(); return false; } } // match breaks date down month = matchArray[1]; // parse date into variables day = matchArray[3]; year = matchArray[4]; if (month < 1 || month > 12) { // check month range alert("Month must be between 1 and 12."); return false; } if (day < 1 || day > 31) { alert("Day must be between 1 and 31."); return false; } if ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) { alert("Month " + month + " doesn't have 31 days!") return false } if (month == 2) { // check for february 29th var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); if (day > 29 || (day == 29 && !isleap)) { alert("February " + year + " doesn't have " + day + " days!"); return false; } } return true; // date is valid } // **************************************************** function ValidateFICODate(obj) { var dateFormat = 'MM/DD/YY'; var isSuccess = false; var objID = obj.id; var hidFICODate = document.getElementById('hidFICODate').value; if (obj.value == '') { alert('Please enter FICO date.' + '\n' + 'Required field.'); //document.frmCustInfo + '.' + obj.id + '.' + focus(); obj.focus(); obj.select(); return false; } // now check if valid date isSuccess = isValidDate(obj, dateFormat); if (!isSuccess) { obj.focus(); obj.select(); return false; } if (isSuccess) { if (obj.value != hidFICODate) { document.getElementById('hidFICODate_Updated').value = 'UPDATED'; document.getElementById('hidFICODate').value = obj.value; } } return isSuccess; } Hello, On a simple form, there is a radio button group with two radio buttons, a text box, and a submit button. The first radio button is checked(selected) by default. The text box input has the onChange event handler so that if the text is changed, the second radio button will be checked(selected). The problem is the input radio name contains a hyphen that breaks the JavaScript and the name can not be changed. What is the correct syntax for referencing a hyphenated form input radio name in the onChange event? Here is the form that works correctly with no hyphen in the input radio name: Code: <form name="myFormGood" action="" onsubmit="return false;"> Good Form with no hyphen in radio button name<br> <input name="radio1" type="radio" value="4" checked> First Option<br> <input name="radio1" type="radio" value="5"> Second Option<br><br> Change the text to select the Second Option<br> <input type="text" name="text1" onChange="document.myFormGood.radio1[1].checked = 'true';" size="10" value=" "><br><br> <input type="button" name="submit" value="It Works!"> </form> Here is the form that breaks the JavaScript because it has a hyphen in the input radio name: Code: <form name="myFormBad" action="" onsubmit="return false;"> Bad Form with hyphen in radio button name breaks JavaScript<br> <input name="radio-1" type="radio" value="4" checked> First Option<br> <input name="radio-1" type="radio" value="5"> Second Option<br><br> Change the text to select the Second Option. Nothing Happens.<br> <input type="text" name="text1" onChange="document.myFormBad.radio-1[1].checked = 'true';" size="10" value=" "><br><br> <input type="button" name="submit" value="It Doesn't Work!"> </form> I have the following form working with on onsumbit function, but I would like to change it so that instead of having to click the purchase button to see total price, you only have to change the quanity text box input. I would welcome any help. I just can not seem to get it to work. Code: <script language="javascript" type="text/javascript"> function checkQuantity(frm) { var succesful = false; var numQuantity; numQuantity = parseInt(frm.Quantity.value); var numTotalPrice; if (numQuantity != 0) { numTotalPrice = numQuantity * 4; frm.TotalPrice.value = numTotalPrice; //new String(numTotalPrice); successful = true; } else { alert("Sorry must order more than 0"); successful = false; } return succesful; } </script> Code: <form action="" onsubmit="return checkQuantity(this)" style="width: 193px"> <table cellpadding="4" style="width:111%"> <tr> <td class="style1"> Quanity:</td> <td class="formInputCell"> <input name="Quantity" type="text" style="width: 55px" /></td> </tr> <tr> <td class="style1"> Total Price $ </td> <td class="formInputCell"> <input name="TotalPrice" type="text" style="width: 55px" /></td> </tr> <tr> <td class="style2"></td> <td><input id="Submit1" type="submit" value="Buy Now" class="buttonstyle" /></td> </tr> </table> </form> |