JavaScript - How To: Select Onchange Alter Another Field On Same Page
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> Similar TutorialsHello guys I have a website which uses several forms to input data, each form contains fields for the user to complete and at the end of the each form the user has the option to proceed or go back. The problem is, on form1 there is a drop down box which determines the content of subsequent forms but when a user partially completes form2 but then goes back to form1 and changes the drop down box selection, the onchange function reloads the subsequent forms but it does not clear the previous form2 values so an error is generated because those inputs are not required with the change made to the drop down box. I have tried setting the ids to zero using getelementbyid on form1 but it does not seem to work presumably because the ids are on form2 not form1? Any thoughts would be much appreciated. 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. 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; } 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> 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'); } ?> Hello All I was hoping you guys can help. I have 3 radio fields which when clicked on I want it to change the background colour of the table its within. The radio fields have the same name so only one can be selected at once. At the moment its changing the background yellow but if I click another radio field its not resetting back to normal (white). Im not sure how to achieve this is javascript... Here is the code im using now: Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <script type="text/javascript" language="javascript"> function swapColor(oCheckbox) { var pop = oCheckbox, checkedcolor = 'yellow'; while (pop.nodeType != 1 || pop.nodeName.toLowerCase() != 'table') pop = pop.parentNode; if (typeof pop.oldcolor == 'undefined') pop.oldcolor = pop.style.backgroundColor; pop.style.backgroundColor = (oCheckbox.checked) ? checkedcolor : pop.oldcolor; } </script> </head> <body> <table> <tr> <td> <input type="radio" name="change" value="0" onchange="swapColor(this) checked" />11111111 </td> </tr> </table> <table> <tr> <td> <input type="radio" name="change" value="1" onchange="swapColor(this)" />22222222 </td> </tr> </table> <table> <tr> <td> <input type="radio" name="change" value="2" onchange="swapColor(this)" />33333333 </td> </tr> </table> </body> </html> I would appreciate any help! Thanks! 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'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! Hello, 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. 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> I've done extensive searching, but each example or explanation i come across is too different from my own, so it's ultimately no use. The problem is that I barely know anything when it comes to Javascript, but yet I'm trying to use it. I have a form on a page. This form contains 6 <select> elements, each with its own <option>Other</option> element. If something isn't listed, the user can choose "Other" and then type into a textbox which appears. I have the following code, which works great if only applied to one <select> element. Code: <select name="How did you hear about us?" id="How did you hear about us?" onchange="makeBox1()"> <option value="0" selected="selected">-- Select --</option> <option value="1">Search Engine</option> <option value="2">Referral</option> <option value="3">Trade Publication</option> <option value="4">Vendor Web Site</option> <option value="5">Your Company Website</option> <option value="6">Direct Mail</option> <option value="7">Other</option> </select> <div id = "inputBox1"></div> <script type = "text/javascript"> function makeBox1() { var a = "<input type = 'text' name = 'box1' id = 'box1' class='form popup'>" if (document.getElementById("How did you hear about us?").value==7) { document.getElementById("inputBox1").innerHTML = a; } else { document.getElementById("inputBox1").innerHTML = ""; } } </script> I've read that you have to combine onchange events, but i have no idea how to do this (i've done plenty of trial and error, trying to make every item unique, but to no avail. How would i add more scripts like the above? Hi All, I have a script that is called by the onchange event on my text field (it compares the date entered into the field and issues an alert if the date is earlier than the current date). This worked great on my data entry form but I also want to use the same script in my update form. In the update form the text field is already receiving a value via php: Code: <input name="DateNeeded" type="text" class="formField" id="DateNeeded" onchange="checkDate(this)" value="<?php echo $row_rstRequestDetails['DateNeeded']; ?>" /> and this is causing my onchange event to fire when the page is loaded. Is there a way to suppress the onchange event for the initial page load? Thanks, Ken Hello, I have this onchange event that occurs after user selection of a dropdown menu. When a user makes a selection it queries the database and delivers some data. The value of the dropdown is stored in a database, but the problem is when the page is refreshed the delivered data disapears, only reappearing if you change the dropdown. How can I make the onchange event run when the page loads so that if there is already a selection, the database data will always be there, only to change if the user changes the selection? Here is the JS: Code: <script type="text/javascript"> function showCustomer(str) {var xmlhttp; 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","getcustomer.asp?q="+str,true); xmlhttp.send();} </script> And the onchange line: Code: <SELECT Name=""customers"" id=""customers"" onchange=""showCustomer(this.value)""> Etc... Please ignore the double sets of quotes. here is all my code for _form.php PHP Code: <?php use_stylesheets_for_form($form) ?> <?php use_javascripts_for_form($form) ?> <html> <head> <script type="text/JavaScript"> function refreshPage(value) { [COLOR="Red"]//need to test here id user selects from the dropdown "zed-catcher" i must display on the page the following: [/COLOR] if ($row->getName() == "zed-catcher") { echo $form['service_code']->renderLabel(); echo $form['service_code']->renderError(); echo $form['service_code']; } [COLOR="Red"]///so the code above is not right...dont know how to code this in java script[/COLOR] window.location.reload(); } </script> </head> </html> <body> <form action="<?php echo url_for('adminservice/'.($form->getObject()->isNew() ? 'create' : 'update').(!$form->getObject()->isNew() ? '?id='.$form->getObject()->getId() : '')) ?>" method="post" <?php $form->isMultipart() and print 'enctype="multipart/form-data" ' ?>> <?php if (!$form->getObject()->isNew()): ?> <input type="hidden" name="sf_method" value="put" /> <?php endif; ?> <table > <tfoot> <tr> <td colspan="2"> <?php echo $form->renderHiddenFields(false) ?> <a href="<?php echo url_for('adminservice/index') ?>">Back to list</a> <?php if (!$form->getObject()->isNew()): ?> <?php echo link_to('Delete', 'adminservice/delete?id='.$form->getObject()->getId(), array('method' => 'delete', 'confirm' => 'Are you sure?')) ?> <?php endif; ?> <input type="submit" value="Save" /> </td> </tr> </tfoot> <tbody> <?php echo $form->renderGlobalErrors() ?> <tr> <th><?php echo $form['name']->renderLabel() ?></th> <td> <?php echo $form['name']->renderError() ?> <?php echo $form['name']?> </td> </tr> <tr> <th><?php echo $form['logo_url']->renderLabel() ?></th> <td> <?php echo $form['logo_url']->renderError() ?> <?php echo $form['logo_url'] ?> </td> </tr> <tr> <th><?php echo $form['wap_home']->renderLabel() ?></th> <td> <?php echo $form['wap_home']->renderError() ?> <?php echo $form['wap_home'] ?> </td> </tr> <tr> <th><?php echo $form['call_center_number']->renderLabel() ?></th> <td> <?php echo $form['call_center_number']->renderError() ?> <?php echo $form['call_center_number'] ?> </td> </tr> <tr> <th><?php echo $form['catcher_id']->renderLabel(); $catcher_id = $form->getObject()->getCatcherId(); $catcher = LpmCatcherPeer::getByCatcherId($catcher_id); $catcher_name = $catcher->getName(); ?></th> <td> <?php echo $form['catcher_id']->renderError() ?> <select name="services"> <?php $catcher_names = LpmCatcherPeer::getByAllNames(); foreach($catcher_names as $row) { ?> <option value="<?php echo $row->getName()."/".$row->getId();?>" <?php if($row->getName() == $catcher_name) echo ' selected="selected"'; ?> [COLOR="Red"]onchange="refreshPage(this.value)"[/COLOR]><?php echo $row->getName();?></option> <?php } ?> </select> </td> </tr> <tr> <th><?php echo $form['price_description']->renderLabel() ?></th> <td> <?php echo $form['price_description']->renderError() ?> <?php echo $form['price_description'] ?> </td> </tr> <tr> <th><?php echo $form['invalid_msisdn_text']->renderLabel() ?></th> <td> <?php echo $form['invalid_msisdn_text']->renderError() ?> <?php echo $form['invalid_msisdn_text'] ?> </td> </tr> <tr> <th><?php echo $form['terms_and_conditions']->renderLabel() ?></th> <td> <?php echo $form['terms_and_conditions']->renderError() ?> <?php echo $form['terms_and_conditions'] ?> </td> </tr> </tbody> </table> </form> </body> please see code and comments in red... dont know how to code it in java script..please help??? many thanks I have a text box with add button. When the add button is clicked i want it to add the contents of the text box as a new line in the select field. I also want a button that would allow me to remove the selected item in the select field. is this possible? Hi All, Firstly - apologies to anyone who has read this in the PHP forum - I was not sure if I needed to post it there or here! I have a PHP form which has an select field (i.e. drop-options) where the different options are populated from a MySQL database as follows: Code: <select size="1" id="category" name="category"> <option value="">Select from drop-list:</option> <?php $sql = "SELECT * FROM `DB1` ORDER BY list_category ASC"; $sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql); while ($row = mysql_fetch_assoc($sql_result)) { if ($row["list_category"]<>'') { echo '<option value="'; echo nl2br(stripslashes(utf8_decode($row["list_category"]))).'">'; echo nl2br(stripslashes(utf8_decode($row["list_category"]))).'</option>'; }; }; ?> </select> Now, the issue I have is that I also have another input field (possibly hidden) in this form which is called 'category_id', and what I want it to do is to automatically populate when the user selects the relevant 'category' from the select field above. EDIT: Sorry - should also have told you that the 'category_id' is associated with the 'category' field above in the same database, DB1. Can anyone recommend any way of doing this? Thanks, Neil I've been tasked to create a form where the user types a numeric item id into a text field. Typing this numeric item id into the field will update a select list when the item id matches a select list value. Can anyone help me with this as I don't know where to start?
I have an existing form with radio buttons and a text input field: <input type="radio" name="recurringEnd" value="yes"> End after <input type="text" name="numberOccurrences" size="1"> occurrences <input type="radio" name="recurringEnd" value="date"> End on <input type="text" name="endDate" size="8"> My client now wants it setup so that if the text field is filled in, the radiobox is automatically selected. Any help on this would be greatly appreciated as I am not a JS programmer. I have a telephone input on my form. It is an optional input for users. The prompt begins with the user having to select a phone type from a select menu, and then continue to the text fields to enter the digits. I would like to have the text fields disabled unless any of the types of phone are selected, but not if a type isn't selected. Here's my HTML code so far: Code: <select name="phoneType1"> <option value="" selected="selected">Type...</option> <option value="Home">Home</option> <option value="Work">Office</option> <option value="Cell">Cell</option> </select> (<input type="text" id="phAreaCode1" name="phAreaCode1" size="2" maxlength="3" onkeyup="moveOnMax(this,'phPrefix1')"/>) - <input type="text" id="phPrefix1" name="phPrefix1" size="2" maxlength="3" onkeyup="moveOnMax(this,'phLine#1')"/> - <input type="text" id="phLine#1" name="phLine#1" size="5" maxlength="4"/> ext.<input type="text" name="phExtension1" size="4" maxlength="4"/> I know that all I need to do to disable the text fields is to type in "disabled" before the name of the field. But, I don't know how to enable it when "Home," "Office," or "Cell" is selected. Thanks for any help. I am finishing up my Form page, and totally forgot to have a numeric only field. So I added it and I can't get it to work. I also am having issues throwing an error when you don't select at least one topping. And are these lines correct? Code: document.cookie = "toppings=" + encodeURIComponent(document.getElementsByName("toppings[]").value); Code: document.cookie = "extra=" + encodeURIComponent(extra); Here is a link to the page hosted on my dropbox http://dl.dropbox.com/u/49211616/dw/...orderPage.html Javascript: Code: function validateOrder () { var crustSelection = document.orderForm.crust.value; var crustPrice; //Adds $1 for Deep DishParmesagn, and Sourdough var count = 0; //Amount of Toppings Selected var choice = ""; //Toppings Selected list var x = ""; //Don't need for the Cookie var extra = 0; //extra charge for toppings over 3 try{ var error = ""; // Initialize Var to store the error messages. if(document.getElementById("delivery").checked != true && document.getElementById("takeout").checked != true) { error=error+"Order Type is required.\n" } if(document.getElementById("fname").value == "") { error = error + "First Name is required.\n"; } if(document.getElementById("lname").value == "") { error = error + "Last Name is required.\n"; } if(document.getElementById("address").value == "") { error = error + "Street address is required.\n"; } if (isNaN(document.getElementById("quantity"))) { error = error + "Enter Pizza Quantity in Numbers Only.\n"; } if(document.getElementById("crust").value == "") { error = error + "Crust Type is required.\n"; } if(document.getElementsByName("toppings").value == 0) { error = error + "Select at Least One Topping.\n"; } if(error == "") { // save all the information in the cookie document.cookie = "firstName=" + encodeURIComponent(document.getElementById("fname").value); document.cookie = "lastName=" + encodeURIComponent(document.getElementById("lname").value); document.cookie = "address=" + encodeURIComponent(document.getElementById("address").value); document.cookie = "order=" + encodeURIComponent((document.getElementById("delivery").checked) ? "delivery" : "takeout"); document.cookie = "quantity=" + encodeURIComponent(document.getElementById("quantity").value); document.cookie = "quantity=" + encodeURIComponent(document.getElementById("quantity").value); document.cookie = "crust=" + encodeURIComponent(document.getElementById("crust").value); document.cookie = "toppings=" + encodeURIComponent(document.getElementsByName("toppings[]").value); alert("Order successfully Placed!"); } else { alert(error); } } catch(ex) { alert("An error occurred!.\n" + "Error Name : " + ex.name + "\nError Message : " + ex.message); } for (var i=1; i<11; i++) { x = document.orderForm['toppings' + i].value; if (document.orderForm['toppings' + i].checked) { choice = choice + " " + x ; count ++; } } if (choice.length <= 0) { choice = choice + "NONE"; } if (count > 3) { extra = (count - 3) * 1 } document.cookie = "extra=" + encodeURIComponent(extra); } </script> HTML: Code: <form name = "orderForm" onsubmit="validateOrder()"> <table width="600" border="0"> <tr> <th scope="col" width="400" align="left"><b>First Name</b><br /><input type="text" id="fname" name="fname" size=30> <br /> <br /> <b>Last Name</b><br /> <input type="text" id="lname" name="lname" size=30> <br /> <br /> <b>Street Address</b><br /> <input type="text" id="address" name="address" size=30> <br /> <br /> <input name="orderType" value="delivery" id="delivery" type="radio">Delivery</font> <input name="orderType" value="takeOut" id="takeout" type="radio">Take Out</font></th> <th scope="col" width="200" align="Left"> How Many Pizzas? <input type="text" id="quantity" name="quantity" size=5> <br /> <br /> <select name="crust" id="crust"> <option selected value="false">Select Crust Type</option> <option value="regular">Regular Crust</option> <option value="thin">Thin Crust</option> <option value="deep">Deep Dish</option> <option value="Parmesagn">Parmesagn Cheese</option> <option value="sourdough">Sourdough</option> </select> <br /> <br /> Select at Least One Topping: <br /> <br /> <input name = "toppings1" type = "checkbox" value = "extraCheese"> Extra Cheese<br> <input name = "toppings2" type = "checkbox" value = "sausage"> Sausage<br> <input name = "toppings3" type = "checkbox" value = "pepperoni"> Pepperoni<br> <input name = "toppings4" type = "checkbox" value = "bacon"> Bacon<br> <input name = "toppings5" type = "checkbox" value = "canadianBacon"> Canadian Bacon<br> <input name = "toppings6" type = "checkbox" value = "mushroom"> Mushroom<br> <input name = "toppings7" type = "checkbox" value = "pineapple"> Pineapple<br> <input name = "toppings8" type = "checkbox" value = "onion"> Onion<br> <input name = "toppings9" type = "checkbox" value = "olive"> Olive<br> <input name = "toppings10" type = "checkbox" value = "greenPepper"> Green Pepper<br></th> </tr> </table> <input name="submit" type="submit" value="submit" /><input name="" type="reset" /> </form> |