JavaScript - Help With Dynamic Select Box Error
Hello all! I am hoping for some coding help as I have been trying to figure out my problem for a couple of days without resolve. I am new to Javascript so this is just test code that eventually will go into a larger project. Here goes:
I have a form that initially creates two select boxes. The 2nd select box option values are determined onchange of the first boxes value using mysql to pull the data from a database. That all works fine. I also have an add button that adds a second set of select boxes dynamically and assigns names and values, etc. This also works fine. My goal is to have the 2nd set of select boxes act the same as the first so that when an option is chosen in the first box the 2nd dynamically populates. This does not work. The first box is created fine but when it tries to create the values in the 2nd from an onchange event I have a problem. This is the code that returns a valid object with the first set of select boxes but is null with the 2nd set. Code: var selbox = document.getElementById(exep); The entire piece of spaghetti code is below. Any help is appreciated. Please be nice as I am still trying to figure out this Javascript stuff. Thanks for any help... Code: <html> <head> <title>Workout testing</title> <SCRIPT language="javascript"> function deleteRow(tableID) { try { var table = document.getElementById(tableID); var rowCount = table.rows.length; for(var i=0; i<rowCount; i++) { var row = table.rows[i]; var chkbox = row.cells[0].childNodes[0]; if(null != chkbox && true == chkbox.checked) { if(rowCount <= 1) { alert("Cannot delete all the rows."); break; } table.deleteRow(i); rowCount--; i--; } } }catch(e) { alert(e); } } </SCRIPT> <script language="javascript"> function setOptions(chosen, form_num) { var musc = "musc_"+form_num; var exep = "exep_"+form_num; //var str = ''; // var elem = document.getElementById('form1').elements; // for(var i = 0; i < elem.length; i++) // { // str += "<b>Type:</b>" + elem[i].type + "  "; // str += "<b>Name:</b>" + elem[i].name + " "; // str += "<b>Value:</b><i>" + elem[i].value + "</i> "; // str += "<BR>"; // } // document.getElementById('lblValues').innerHTML = str; var selbox = document.getElementById(exep); selbox.options.length = 0; if (chosen == "0") { selbox.options[selbox.options.length] = new Option('First select a muscle group','0'); } <? $car_result = mysql_query("SELECT muscle FROM work_muscle") or die('Something is wrong: ' . mysql_error()); while(@($c=mysql_fetch_array($car_result))) { ?> if (chosen == "<?=$c['muscle'];?>") { <? $c_id = $c['muscle']; ; $mod_result = mysql_query("SELECT exercise FROM work_exercise WHERE muscle='$c_id'") or die('Something is wrong: ' . mysql_error()); while(@($m=mysql_fetch_array($mod_result))) { ?> selbox.options[selbox.options.length] = new Option('<?=$m['exercise'];?>','<?=$m['exercise'];?>'); <? } ?> } <? } ?> } </script> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>create DOM table</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <script type="text/javascript"> function makeTable() { //give the new table unique name var form_num = document.getElementsByTagName("table").length; row=new Array(); cell=new Array(); row_num=1; //edit this value to suit cell_num=6; //edit this value to suit tab=document.createElement('table'); var table_id = 'newtable_'+form_num; tab.setAttribute('id',table_id); tbo=document.createElement('tbody'); for(c=0;c<row_num;c++){ row[c]=document.createElement('tr'); for(k=0;k<cell_num;k++) { cell[k]=document.createElement('td'); //cont=document.createTextNode((c+1)*(k+1)) //cell[k].appendChild(cont); row[c].appendChild(cell[k]); } tbo.appendChild(row[c]); } tab.appendChild(tbo); document.getElementById('mytable').appendChild(tab); changeBorder(table_id, form_num); } function changeBorder(table_id, form_num){ document.getElementById(table_id).border="1"; pop_cells(table_id, form_num); } function pop_cells(table_id, form_num) { var table = document.getElementById(table_id); var colCount = table.rows[0].cells.length; //create the first checkbox var selcheck = document.createElement("input"); selcheck.type = "checkbox"; selcheck.name = "chk[]"; //create the first select box var selbox = document.createElement("select"); var musc_opt = "musc_"+form_num; selbox.name = "musc_"+form_num; selbox.id = "id_"+form_num; //var test_ops = javascript:setOptions(document.form1.'+musc_opt+'.options [document.form1.'+musc_opt+'.selectedIndex].value,'+selbox.name+'); //selbox.setAttribute("onchange", function(){setOptions(test_ops);}); selbox.onchange = function(){setOptions(this.value,form_num);}; selbox.options[selbox.options.length] = new Option('Select a muscle group','0'); <? $car_result = mysql_query("SELECT muscle FROM work_muscle") or die('Something is wrong: ' . mysql_error()); while(@($c=mysql_fetch_array($car_result))) { ?> selbox.options[selbox.options.length] = new Option('<?=$c['muscle'];?>','<?=$c['muscle'];?>'); <? } ?> //create the 2nd select box var selbox2 = document.createElement("select"); selbox2.name = "exep_"+form_num; selbox2.id = "id_"+form_num; selbox2.size = "1"; selbox2.options[selbox2.options.length] = new Option('First select a muscle group','0'); //<? //$car_result = mysql_query("SELECT exercise FROM work_exercise") or die('Something is wrong: ' . mysql_error()); //while(@($c=mysql_fetch_array($car_result))) { //?> // selbox2.options[selbox2.options.length] = new Option('<?=$c['exercise'];?>','<?=$c['exercise'];?>'); //<? //} //?> var target0 = table.rows[0].cells[0]; var target1 = table.rows[0].cells[1]; var target2 = table.rows[0].cells[2]; // fire target1.appendChild(selcheck); target1.appendChild(selbox); target1.appendChild(selbox2); } </script> </head> <body> <form name="form1"><div align="center"> <INPUT type="button" value="Add Row" onclick="makeTable()" /> <INPUT type="button" value="Delete Row" onclick="javascript:deleteRow(this)" /> <TABLE id="newtable" width="350px" border="1"> <TR><TD><INPUT type="checkbox" name="chk[]"/></TD> <td><select name="musc_0" size="1" onchange="javascript:setOptions(document.form1.musc_0.options [document.form1.musc_0.selectedIndex].value, 0);"> <option value="0" selected>Select a muscle group</option> <? $result = mysql_query("SELECT * FROM work_muscle") or die(mysql_error()); while(@($r=mysql_fetch_array($result))) { ?> <option value="<?=$r['muscle'];?>"><?=$r['muscle'];?></option> <? } ?> </select></td> <td> <select name="exep_0" size="1"> <option value=" " selected>First select a muscle group</option> </select></td></tr> </div></table><div id="mytable"></div><div id="lblValues"></div> </form> </body> </html> Similar TutorialsHope some one can assist me Below is my code which works fine. I need to be able to select more than one of the options at the same time. The code at the moment will only select one option rather than all my options. Any advice would be great. <HTML> <HEAD> <title>MDT Role and Application Selection Application - Gen-i</title> <!-- Example of the multiple selections Sub RunScript For i = 0 to (Dropdown1.Options.Length - 1) If (Dropdown1.Options(i).Selected) Then strComputer = strComputer & Dropdown1.Options(i).Value & vbcrlf End If Next Msgbox strComputer End Sub --> <script> function setOptions(chosen) { var selbox = document.myform.opttwo; selbox.options.length = 0; if (chosen == " ") { selbox.options[selbox.options.length] = new Option('Please select one of the options above first',' '); } if (chosen == "1") { selbox.options[selbox.options.length] = new Option('Microsoft Project','Microsoft Project selected'); selbox.options[selbox.options.length] = new Option('Microsoft Visio','Microsoft Visio selected'); selbox.options[selbox.options.length] = new Option('Cognos Application','Cognos Application selected'); } if (chosen == "2") { selbox.options[selbox.options.length] = new Option('Microsoft Project','Microsoft Project selected'); selbox.options[selbox.options.length] = new Option('Microsoft Visio','Microsoft Visio selected'); selbox.options[selbox.options.length] = new Option('Cognos Application','Cognos Application selected'); selbox.options[selbox.options.length] = new Option('Oracle Discoverer','Oracle Discoverer selected'); selbox.options[selbox.options.length] = new Option('At Risk 5.55','At Risk 5.55 selected'); } if (chosen == "3") { selbox.options[selbox.options.length] = new Option('Microsoft Project','Microsoft Project selected'); selbox.options[selbox.options.length] = new Option('Microsoft Visio','Microsoft Visio selected'); selbox.options[selbox.options.length] = new Option('Vulcan 8','Vulcan 8 selected'); selbox.options[selbox.options.length] = new Option('Autocad Lite 2010 Lite','Autocad Lite 2010 Lite selected'); selbox.options[selbox.options.length] = new Option('Autocad Lite 2010 Full','Autocad Lite 2010 Full selected'); selbox.options[selbox.options.length] = new Option('Aquire','Aquire selected'); selbox.options[selbox.options.length] = new Option('WellCad','WellCad selected'); selbox.options[selbox.options.length] = new Option('ArcGis','ArcGis selected'); selbox.options[selbox.options.length] = new Option('QuickMap','QuickMap selected'); } } </script> <HTA:APPLICATION border="thin" borderStyle="normal" caption="yes" maximizeButton="yes" minimizeButton="yes" showInTaskbar="no" innerBorder="yes" navigable="yes" scroll="auto" scrollFlat="yes" /> <script LANGUAGE="VBScript"> Sub Window_onLoad window.resizeTo 600,720 End Sub </script> </head> <body style="{background-image:url('bg2.jpg'); background-repeat:no-repeat;}"> <CENTER> <img src="logo.gif" /> <h2 style="font-size: 12pt; font-family: Arial; color: #000">Please select the required role - Gen-i</h2> <div style="font-size: 10pt; font-family: Arial; color: #298FFF"> <form name="myform"><div align="center"> <b>Select a Role:</b> <br /> <select name="optone" size="1" onchange="setOptions(document.myform.optone.options [document.myform.optone.selectedIndex].value);"> <option value=" " selected="selected"> </option> <option value="1">General</option> <option value="2">Technical</option> <option value="3">Finance</option> </select> <br /><br /><b>Select Applications:</b> <br /> <select name="opttwo" size="10" multiple> <option value=" " selected="selected">Please select one of the options above first</option> </select> <p></p> <input type="button" name="go" value="Value Selected" onclick="alert(document.myform.opttwo.options [document.myform.opttwo.selectedIndex].value);"> </div></form> </body> </html> 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. 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? I have a website I am currently debugging, http://display.ist-apps.com/. When you select a ski resort, then go on to select a date, the dates relating to that ski resort show. However if you then go back and select another ski resort, the dates do not update they still continue to show the ones from the ski resort you originally selected. This is a debug piece of work I am doing based on something someone else built so it's a bit of a toughie, any help is appreciated. Here is the related (I think) JS file. Code: (function($){$.fn. dynamicResortSelect = function(options) { var defaults = { 'dateFormat' : 'dd/mm/y', 'forceDatePickerZindex' : false, 'uris' : { 'get_availiable_durations' : '/get-availiable-durations', 'get_availiable_start_dates' : '/get-availiable-start-dates'}}; var options = $.extend(defaults, options); var datePickerDrawn = false; var durationsDrawn = false; var currentMonth = ''; var resortTitle = ''; var resorts = []; function _updateDurations(dateText, durationsValue) { $.getJSON(options.uris.get_availiable_durations, {'resort_title': resortTitle, 'start_date': dateText}, function (data) { var options = {0:'Duration...'}; for (var i in data) { options[data[i]] = data[i]+' Nights' } if (durationsValue < 0) { $('.duration_container').addClass('disabled'); $('select[name="duration"]') .selectBox('disable') .selectBox('value', 0); } else { $('.duration_container').removeClass('disabled'); $('select[name="duration"]') .selectBox('options', options) .selectBox('enable') .selectBox('value', durationsValue); } }); } /* function _isValidDate(dates, date) { var formattedMonth = date.getMonth()+1; if (formattedMonth < 10) formattedMonth = '0'+formattedMonth; var formattedDate = date.getDate(); if (formattedDate < 10) formattedDate = '0'+formattedDate; var dateFormatted = date.getFullYear()+'-'+formattedMonth+'-'+formattedDate+' 00:00:00'; return [$.inArray(dateFormatted, dates) != -1]; }*/ function _drawDatePicker(startDate, endDate, dates) { $('.date_picker_conatiner').removeClass('disabled'); $('.date_picker_conatiner .date_picker').removeAttr('disabled').datepicker( { dateFormat: options.dateFormat, minDate: startDate, maxDate: endDate, beforeShow: function() { if (typeof(options.forceDatePickerZindex) == 'number') setTimeout('jQuery("#ui-datepicker-div").css("z-index", "'+options.forceDatePickerZindex+'")', 1); }, beforeShowDay: function(date) { var formattedMonth = date.getMonth()+1; if (formattedMonth < 10) formattedMonth = '0'+formattedMonth; var formattedDate = date.getDate(); if (formattedDate < 10) formattedDate = '0'+formattedDate; var dateFormatted = date.getFullYear()+'-'+formattedMonth+'-'+formattedDate+' 00:00:00'; return [$.inArray(dateFormatted, dates) != -1]; }, onSelect: function(dateText, inst) { _updateDurations(dateText, 0); } }); } function _updateDatePicker(value) { if (datePickerDrawn) $('.date_picker').destroy(); resortTitle = resorts[value]; $.getJSON(options.uris.get_availiable_start_dates, {'resort_title': resortTitle}, function (data) { var startDate = data[0]; var endDate = data[data.length-1]; currentMonth = startDate.substring(5, 7); startDate = _buildDate(startDate); endDate = _buildDate(endDate); _drawDatePicker(startDate, endDate, data); }); return true; } function _buildDate(text) { ret = new Date( text.substring(0, 4), (text.substring(5, 7) - 1), text.substring(8, 10)); return ret; alert('alerting'); } return this.each(function() { var alreadyPopulated = $('select[name="duration"]').val() != 0; $('select[name="first_hotel_id"] option').each(function() { resorts[$(this).val()] = $(this).text(); }); // $('select[name="first_hotel_id"]').selectBox(); $('select[name="first_hotel_id"]').change(function() { var value = $(this).val(); _updateDatePicker(value); /* if (durationsDrawn) $('select[name="duration"]').*/ }); // $('select[name="duration"]').selectBox(); // alert("true"); if (alreadyPopulated) { _updateDatePicker($('select[name="first_hotel_id"]').val()); durationsValue = $('select[name="duration"]').val(); _updateDurations($('.date_picker_conatiner .date_picker').val(), durationsValue); } }); }})(jQuery); 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, i'm trying to insert a dynamic js file which contains multiple functions in it (for the example : function x, function y) and it seems that my google chrome doesn't really like it so much is there anyway you know i can bypass it and make it work and both web browsers code examples: // this is where the js file supposed to go <script id="ScriptFile"> </script> //1.js contains function x and function y document.getElementById('ScriptFile').src = "/Mysite/js/1.js" later on i need to preform some actions with function x & y. Couple more issues i need to explain first there are number of js files (1,2,3 .... n ) which all contain the same functions but with different data so i cant register them hard-coded if i type the function x into the "ScriptFile" block, it does work.. its not the function problem. same goes if i include it as source in the "ScriptFile" block (<script id="ScriptFile" src="/Mysite/js/1.js") this only gives me an error while using chrome, works perfectly fine under explorer the error says it cant find function x. thanks alot! Hi All, i know how to create a dynamic form or DIv ..but what i do not know is how to create a dynamic form/ or div into a previous dynamic one.. i need basically to see 5 dynamic forms / DIV in cascade where each one trigger the one coming after.. For what i need that : i have my user inserting information on the level 1. let say Copagny info 2- then he will be asked if he wants to add a sub level information ( subform) for that compagny or even many subforms at the same level .. and so on... 3- those sub level ( subforms ) can also call their respective subforms.. Any idea how to design this ? thanks I have made a script where you can add extra fields, and next to the row is a span that automatically displays the outcome from a calculation of three fields in that row. i.e. Q x (B - A) = total. Here is the bit that does the calculation: Code: function advCalc(selected) { var result = Number(document.formmain.elements["quantity"+selected].value) * (Number(document.formmain.elements["provideamount"+selected].value) - Number(document.formmain.elements["supplyamount"+selected].value)) ; result = result.toFixed(2) ; result = addCommas(result) ; document.getElementById("total"+selected).innerHTML = result ; } The bit that adds a new row of fields is: Code: function addPart(divName){ var newdiv = document.createElement('div') ; newdiv.setAttribute('id', 'partrow' + counter) ; newdiv.setAttribute('style', 'clear:both;') ; newdiv.innerHTML = "<div style='float:left;width:40px;text-align:center;margin:5px 5px 0px 0px;'>\r<input onkeyup=\"advCalc('" + counter + "')\" id=' quantity " + counter + "' type='text' value='1' size='1'/>\r</div>\r<div style='float:left;width:100px;text-align:left;margin:5px 0px 0px 0px;'>\r<input id='manufacturer" + counter + "'type='text' value='' size='9'/>\r</div>\r<div style='float:left;width:95px;text-align:left;margin:5px 5px 0px 0px;'>\r<input id='partnumber" + counter + "'type='text' value='' size='9'/>\r</div>\r<div style='float:left;width:80px;text-align:left;margin:5px 5px 0px 0px;'>\r<input id='supplier" + counter + "'type='text' value='' size='4'/>\r</div>\r<div style='float:left;width:100px;text-align:left;margin:5px 5px 0px 0px;'>\r<input id='type" + counter + "'type='text' value='' size='6'/>\r</div>\r<div style='float:left;width:85px;text-align:left;margin:5px 5px 0px 0px;'>\r<input id='deliverytime" + counter + "'type='text' value='' size='13'/>\r</div>\r<div style='float:left;width:40px;text-align:left;margin:5px 0px 0px 45px;'>\r<select id='supplyCurrency" + counter + "'>\r<option value='pound' selected='selected'>£</option><option value='dol'>$</option><option value='euro'>€</option></select>\r</div>\r<div style='float:left;width:15px;text-align:left;margin:5px 5px 0px 0px;'>\r<input onkeyup=\"advCalc(\'" + counter + "\')\" id=' supplyamount " + counter + "'type='text' value='' size='3'/>\r</div>\r<div style='float:left;width:40px;text-align:left;margin:5px 0px 0px 45px;'>\r<select name='provideCurrency" + counter + "'><option value='pound' selected='selected'>£</option><option value='dol'>$</option><option value='euro'>€</option></select>\r</div>\r<div style='float:left;width:15px;text-align:left;margin:5px 5px 0px 0px;'>\r<input onkeyup=\"advCalc(\'" + counter + "\') id=' provideamount " + counter + "' type='text' value='' size='3'/>\r</div>\r<div style='float:left;width:20px;text-align:left;margin:5px 0px 0px 45px;'>\r<strong>£</strong>\r</div>\r<div style='float:left;width:40px;text-align:left;margin:5px 5px 0px 0px;'><span id=' total " + counter + "'></span></div> \r" ; document.getElementById(divName).appendChild(newdiv) ; counter++ ; } The problem I am having is that it works fine for the first row which is hardcoded as e.g. id="provideamount0" etc. It isn't working for any other fields added but I can't see what is wrong I've been having problems getting my select option to change the options of another select option. I'm not much of a javacsript coder, so I'm at a lost. When I select the first option nothing appears in the second option. here's the javascript code: Code: function createOption(OptionText, OptionValue){ var temp = document.captcha_form("option"); temp.innerHTML = OptionText; temp.value = OptionValue; return temp; } function valChange(){ var firstList = document.getElementById("emailaddress"); var secondList = document.getElementById("subject"); while(secondList.hasChildNodes()) secondList.removeChild(secondList.childNodes[0]); switch(firstList.value){ case "1":{ secondList.appendChild(createOption("Report Site Browsing Issue", Report Site Browsing Issues)); secondList.appendChild(createOption("Report Page Errors", Report Page Errors)); secondList.appendChild(createOption("Other", Other)); break; } case "2":{ secondList.appendChild(createOption("Report Unauthorized Game", Report Unauthorized Game)); secondList.appendChild(createOption("Report Spam", Report Spam)); secondList.appendChild(createOption("Report Harassment", Report Harassment)); secondList.appendChild(createOption("Report Illegal Activities", Report Illegal Activities)); secondList.appendChild(createOption("Request Account Removal", Request Account Removal)); break; } // .... default:{ secondList.appendChild(createOption("Please select from the first list", "")); break; } } } window.onload = valChange; this is the form code Code: <div class="mailto_form"> <form method="POST" id="captcha_form" name="captcha_form" action="../includes/mailform.php"> <div style="padding-bottom: 1em;">Choose Recipient: <select name="emailaddress" id="emailaddress" onchange="valChange();"> <option value=""></option> <option value="1">Webmaster</option> <option value="2">Admin</option> </select> </div> <div style="padding-bottom: 1em;">Subject: <br /><select name="subject" id="subject"> </div> <div style="padding-bottom: 1em;">From: <br /><input type="text" name="email" id="email" value=""> </div> <div style="padding-bottom: 1em;">Enter the text contained in the image into the text box: <br /><img src="../includes/captcha.php" /> <br /><input type="text" name="userpass" value=""> </div> <div style="padding-bottom: 1em;">Message: <br /><textarea name="message" id="message" rows="10" cols="60"><?php echo "</tex" . "tarea>"; ?> </div> <div style="padding-bottom: 1em;"><input name="submit" type="submit" value="Submit"> </div> </form> </div> Link to the page http://www.netgamegurus.com/contact/ Hey chaps, hope someone can help with this: I have a PHP form, with a couple of dynamic Select menus, which are populated from two SQL tables: // tbl_main_colour: Code: ID, NAME 1, Red 2, Blue 3, Green // tbl_shade_colour: Code: ID, NAME, FK_MAIN_COLOUR_ID 1, Light Red, 1 2, Dark Red, 1 3, Light Blue, 2 4, Dark Blue, 2 5, Light Green, 3 6, Dark Green, 3 What I'm after is something to filter the second select option, after the first select option has been chosen // Select 1: Code: Red // Select 2: Code: Light Red Dark Red I'm pretty sure this is possible, but not sure how to go about it, any help would be most appreciated. Hey Guys When a user changes the select list called "reason_code_master" I need the uodatecodes() function to update all the other select list with the id of "reason_codes" with the same . How can I do this. <select size='1' onchange="updatecodes()" name='reason_code_master'> <option value='' > - SET REASON - </option> <option value='BROKEN' >BROKEN</option> <option value='ENTERED' >ENTERED</option> <option value='SHORT' >SHORT</option> </select> <select size='1' name='reason_codes' id='reason_codes'> <option value='' > - SET REASON - </option> <option value='BROKEN' >BROKEN</option> <option value='ENTERED' >ENTERED</option> <option value='SHORT' >SHORT</option> </select> <select size='1' name='reason_codes' id='reason_codes'> <option value='' > - SET REASON - </option> <option value='BROKEN' >BROKEN</option> <option value='ENTERED' >ENTERED</option> <option value='SHORT' >SHORT</option> </select> <select size='1' name='reason_codes' id='reason_codes'> <option value='' > - SET REASON - </option> <option value='BROKEN' >BROKEN</option> <option value='ENTERED' >ENTERED</option> <option value='SHORT' >SHORT</option> </select> <select size='1' name='reason_codes' id='reason_codes'> <option value='' > - SET REASON - </option> <option value='BROKEN' >BROKEN</option> <option value='ENTERED' >ENTERED</option> <option value='SHORT' >SHORT</option> </select> Hello, I am trying to make a simple code that has a selection list (with the choice fruit or veggie). When the user chooses fruit, the second list displays the options apple, orange, banana. When the user changes their choice to veggie, the second select list then contains carrot, corn, potatoes (and the apple, orange, banana disappear). I need some advice on how to do this Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Untitled</title> </head> <body> <form name = "form1"> <fieldset> <legend>Fruit or Veggie</legend> <select name = "S1"> <option name = "fruit">Fruit </option> <option name = "veggie">Veggie</option> </select> <select name = "S2" </select> </fieldset> </form> <script language="JavaScript" type="text/javascript"> ??? </script> </body> </html> Hi JS Experts, I am working on a class registration system that requires students to register for a main class (101, 102 or 103). The student is supposed to select one main course as well as provide a second choice in case the first is not available. I have two dropdown select fields to capture data 1) Choice -1: 101 / 102 / 103 ( Student needs to select one - Reading the classID from classes table) 2) Choice -2: 101 / 102 / 103 ( If student selects 101 in Choice-1 then the only classes available under Choice-2 should be 102 or 103). How can I accomplish the above? Further to this there are two fields on the form where I would like to auto populate based on what they have selected in Choice-1 and Choice-2. For Example: If a parent selects choice1: 101 the child Choice1 field should autopopulate with 100. If a parent selects Choice2: 201 the child Choice2 field should autopopulate with 200 Any help would be really appreciated. Thanks Vinny I've got some directory list boxes on the site I'm working on. I made them big and fixed rather than drop-down so they're easier to use in this context. But I had to enable the "multiple" attribute to make that work. The site has no provision for multiple selections so it's a tad annoying when the search function selects more than one name in the list. It doesn't really affect the site's operation but it could be confusing to some people. Is there a way to make the listbox show multiple selections without allowing multiple selections? Thanks for any help. <select onchange="display.apply(this, this.value.split(','))" multiple="multiple" id="People" name="People" style="border-style: none; height:244px; width:220px; margin-bottom: 15px;"> <option>Loading</option> </select> Ok so I'm making this form which when a selection is made in one box it will run through the javascript(function getMgmtHours), and update the div(mgmthours). Then another box shows up allowing another selection to be made which runs through the javascript(function getDays) and updates another div(mgmtdate). My problem is that when I use the second box to run through javascript, it overwrites what shows up in the first div (mgmthours) when it should be updating a different div (mgmtdate). Any ideas what I can do to get it update the relevant div and not overwrite the other one? Here is part of the javascript I have in my page head: Code: function getMgmtHours(str) { if (str=="") { document.getElementById("mgmthours").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("mgmthours").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","getmgmthours.php?dist="+str,true); xmlhttp.send(); } function getDays(str) { if (str=="") { document.getElementById("mgmtdate").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("mgmtdate").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","getdates.php?sunday="+str,true); xmlhttp.send(); } Here is the HTML/PHP portion being used: PHP Code: echo "<p>"; echo "Submit hours:"; echo "<form>"; echo "<select name='district' onchange='getMgmtHours(this.value)'>"; echo "<option value=''>Select a district:</option> <option value='1'>1</option> <option value='3'>3</option> <option value='4'>4</option>"; echo "</select>"; echo "</form>"; echo "</p>" echo "<p>"; echo "<form action='./hours.php' method='post' onSubmit='return checkMgmtHours'>"; echo "Weekending Day: "; echo "<select name='weekending' onchange='getDays(this.value)'>"; echo "<option value=''>Choose a Date:</option>"; while ($week < 32) { $nextsunday = strtotime("next Sunday"); if ($week > 0) { $timestamp = strtotime("-" . $week . " week", $nextsunday); } else { $timestamp = $nextsunday;} $weekending = date('M. d, Y', $timestamp); echo "<option value='" . $weekending . "'>" . $weekending . "</option>"; $week = $week + 1; } echo "</select>"; echo "<div id='mgmtdate' />"; echo "<div id='mgmthours' />"; echo "</p>"; Edit: Also, after getMgmtHours() runs, I can still use both getDays and getMgmtHours, howeer once I used getDays, I am no longer able to use getMgmtHours w/o refreshing the page. I have a select box that has ~7000 options, that based on a different dropdown select & input field, gets filtered to 0 - 300 entries. I have another select dropdown that has 13000+ options in total for all the ~7000 entries, but each entry may have 1 to 5 options of these 13000. Is there a way to change the options of the last select dropdown based on what the user chooses in the filtered select box? Currently the idea I'm having is to have the browser load all 13000+ items and filter out the ones that don't apply to the currently selected item, but I'm not sure what kind of lag the user would experience while the browser loads & filters through all these items. Any help would be appreciated. Thanks. (just started JS 2 weeks ago) -- this is also my first time posting here, if my post isnt following the proper template let me know and Ill fix it .. Thanks so much for taking the time to check this out in advance Im trying to make the first ul tag in the each slideMenus[] array index values have a position of left = 0px I keep recieving this error however ____________________________________________________ Error: slideMenus[i].getElementsByTagName("ul").style is undefined Line: 63 ------------------------------------------------------------------ the script in question is in [code]. Could someone tell me if I am just making a syntax error if not ill try redoing the whole thing. window.onload = makeMenus var currentSlide = null var timeID = null leftPos = 0 function makeMenus(){ var slideMenus = new Array() var allElems = document.getElementsByTagName("*") var slideListArr = new Array() for(var i=0 ; i < allElems.length ; i++){ if(allElems[i].className = "slideMenu") slideMenus.push(allElems[i]) } for(var i=0 ; i < slideMenus.length ; i++){ slideMenus[i].onclick = showSlide; Code: slideMenus[i].getElementsByTagName("ul")[0].style.left = "0px"; } document.getElementById("head").onClick = closeSlide document.getElementById("main").onClick = closeSlide } function showSlide(){ var slideList = this.getElementsByTagName("ul")[0] // mess with this if((currentSlide != null) && (currentSlide.id == slideList.id)) {closeSlide()} else{ closeSlide(); var currentSlide = slideList; currentSlide.style.display = "block"; timeID = setInterval('moveSlide()', 1); } } function closeSlide(){ if(currentSlide){ clearInterval(timeID); currentSlide.style.left = "0px" currentSlide.style.display = "none"; var currentSlide = null } } function moveSlide(){ var leftPos = leftPos + 5; if(leftPos <= 220) {currentSlide.style.left = leftPos + "px"} else{ clearInterval(timeID); var leftPos = 0} } I have a dynamic website where my client can upload pictures to, i have php dynamically show the images and etc, i also have php assign each photo an id number. Basically what it is each photo dynamically gets id=$i++. So every photo uploaded it goes up one higher. Now i wanted to make it so in javascript the same happens, the id is dynamically i++ but im not very good in javascript so i was hoping i could get some help. Basically i want it to be something like this. (unless u know a better way of doing the same kind of effect) Code: var i=0; $(document) .ready(function(){ setTimeout(function () {$("#i++").fadeOut("slow");}, 100); setTimeout(function () {$("#i++").fadeIn("fast");}, 400); }); I just need help getting the i++ to work. Hello all. I am currently viewing various reports based on a location chosen by a dropdown. When I select GO, the page sends the location to a popup, which then queries based on that location and displays the graph on the popup window. What I want to do is to eliminate the popup and send the location to a <div> on the same page and then have the query run and display the graph on the same page. Is this possible, or do Divs have to be static content? Thanks, Parallon |