www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 18

Thread: [RESOLVED] Javascript - List data in select option from input within same form

  1. #1
    Join Date
    Jul 2012
    Posts
    10

    resolved [RESOLVED] Javascript - List data in select option from input within same form

    Hello All,

    Here's what I'm trying to do:
    Simply put, I'm creating a configuration form to get settings from an end-user to setup a system for them. I've created a single page where they would enter the relevant form data. In one part, I need the user to list the categories that will be using for items, then when they get to filling out the items, I need them to have the ease of simply choosing the option they've already spent time filling out.

    I tried searching for this but maybe I'm not using the right terms.

    Along with this, I need the changes to take place without refreshing the page and I'm trying to keep this simple to not have to include other things like Ajax.

    What type of output I'm looking for:
    Using the form below, I'm trying to make it work like the following:
    * End-user adds up to 20 category names in 'Section 1'
    * When end-user get to 'Section 2', they fill in the item name, then when they click the category drop down, it gives them a list of the X number of categories they listed in 'Section 1'.

    Here's what the form is going to look like roughly:
    HTML Code:
    <form action="" method="">
    
    <h3>Section 1:</h3>
    
    Please list your categories:<br />
    Cat 1: <input type="text" name="cat1Nam" value="" OnBlur=""><br />
    Cat 2: <input type="text" name="cat2Nam" value="" OnBlur=""><br />
    Cat 3: <input type="text" name="cat3Nam" value="" OnBlur=""><br />
    Cat 4: <input type="text" name="cat4Nam" value="" OnBlur=""><br />
    
    
    
    <h3>Section 2:</h3>
    
    Please list your items and choose your categories for them:<br />
    Item 1: <input type="text" name="itm1Nam" value="">
            <select name="itm1list" onClick="">
              <option value=""></option>
              <option value=""></option>
              <option value=""></option>
              <option value=""></option>
            </select>
    <br />
    Item 2: <input type="text" name="itm2Nam" value="">
            <select name="itm2list" onClick="">
              <option value=""></option>
              <option value=""></option>
              <option value=""></option>
              <option value=""></option>
            </select>
    <br />
    Item 3: <input type="text" name="itm3Nam" value="">
            <select name="itm2list" onClick="">
              <option value=""></option>
              <option value=""></option>
              <option value=""></option>
              <option value=""></option>
            </select>
    
    
    
    <br />
    <br />
    <br />
    
    <input type="submit" value="Submit" />
    
    
    </form>
    My biggest issue with this:
    * Pretty n00b-like (working on that though )
    * I'm having a hard time understanding out to pull data from INPUT TEXT field and placing it as an OPTION in the select field.
    * I only think that using onBlur/onClick will help with getting the data without refreshing the page
    * I'm not sure how to continually add just enough options to the select field (example: They enter 5 categories and when they get to item, it only shows the 5 where-as if they enter 15, it shows 15 options

    I started writing the functions and lost myself while trying to figure out how to meld them to work with each other:
    Code:
    function setCat (form) {
        var setIt = form.catName.value; // not sure if I need to make it look for cat#Nam - maybe using i++ or something
      }
    
    function getCat (form) {
        var getIt = form.itm2list.value; // not sure if I need to make it look for itm#list - maybe using i++ or something
      }
    I just want to say Thanks in advanced for looking at this. I hope at some point I can help others in the same way.

  2. #2
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,270
    Try something like this :
    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta name="generator" content="PSPad editor, www.pspad.com">
    <title></title>
    <style type="text/css">
    h3 {margin:0;padding:5px;}
    p {margin:0;padding:2px 0 3px;}
    input{text-align:center;}
    div {display:block;width:500px;margin:0 auto;}
    </style>
    </head>
    <body>
    	<form action="" method="">	
    		<div id="cat">		
    			<fieldset>		
    				<legend>Categories
    				</legend>		
    				<p>Please list your categories:
    				</p>		
    				<p>
    					<input type="text" id="newCat" value="New categorie" onfocus="rmvDfl(this)" onblur="excAct(this)">
    				</p>		
    			</fieldset>	
    		</div>
    		<div id="itm">
    			<fieldset>
    				<legend>Items
    				</legend>Please list your items and choose your categories for them:<br />
    				<input type="text" id="newItm" value="">          
    				<select id="itmLst" onClick="">          
    				</select>
    			</fieldset>
    		</div>
    	</form>
    <script type="text/javascript">
    // A simple shortcut
    function $(id) {return document.getElementById(id);
    }
    // To remove the default value
    function rmvDfl(i){
    	if (i.value==i.defaultValue) {i.value="";if (document.selection && document.selection.clear) document.selection.clear();}
    }
    var nmbCat=0;
    // To retrieve the default value or to execute the action
    function excAct(i){
    	if (i.value=='') i.value=i.defaultValue;
    	else if (i.id=='newCat') {
    		// We create a new childNode for cat (in fact is first childNode the fieldset) 
    		nmbCat++;
    		var p=document.createElement('p');
    		p.id='cat'+nmbCat;$('cat').childNodes[0].appendChild(p);
    		p.innerHTML=i.value;
    		// We modify the select 
    		var o=$('itmLst').options
    		o[o.length]=new Option(i.value,i.value);
    		// We attach an event to remove the categorie 
    		p.onclick=function(){this.parentNode.removeChild(this);
    			nmbCat--;
    			var o=$('itmLst');o.value=this.innerHTML;
    			o.options[o.selectedIndex]=null;return false}
    	}
    }
    </script>
    </body>
    </html>
    I am not sure that is the better choice but it can give ideas. Then you have only to make the same thing (or better) for items...
    Last edited by 007Julien; 07-23-2012 at 09:30 PM.

  3. #3
    Join Date
    Jul 2012
    Posts
    10
    Hello 007Julien,

    Thanks for your time on this. I tried your suggestion but it doesn't seem to do anything. Also, the javascript itself is pretty complex compared to what I'm working with, but when I evaluated what you provided, it only listed the fields, it didn't have any actual reactions when I typed the data in and it didn't list anything in the drop down (tested Chrome and IE).

    Is there something I'm missing?

    As far as 'Categories', they'll only have the option of adding up to 20. Then, when they start to add the items (which I'll give them about 20 to 40 available text input lines), it's when they click the 'Category Dropdown' that will show the categories the listed before.

    Would like kind of like:

    CATEGORIES:
    1. _Cars_________________
    2. _Trucks_______________
    3. _Pencils_______________
    4. _Other________________
    5. ______________________
    6. ______________________
    7. ______________________
    8. ______________________
    9. ______________________
    10. _____________________
    (to 20... but I've hidden the last 10 to make the form nicer)

    Then... they get to the Items and it looks kind of like this:

    ITEMS:
    1. _Nova_____ CAT: (option of: Cars, Trucks, Pencils, Other)
    2. _Honda_____ CAT: (option of: Cars, Trucks, Pencils, Other)
    so on and so on...

    The end-user types in the item name, then they click the drop down to have the options they already typed in the category section.

  4. #4
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,270
    The proposed script works but the onblur event is confusing especially with the other clicks...
    This unachieved script is perhaps cleaner ?
    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta name="generator" content="PSPad editor, www.pspad.com">
    <title></title>
    <style type="text/css">
    h3 {margin:0;padding:5px;}
    p {margin:0;padding:2px 0 3px;}
    input{text-align:center;}
    div {display:block;width:500px;margin:0 auto;}
    span {color:#909;cursor:pointer;}
    .dsb {background:#eee;}
    .act {background:#fff;}
    </style>
    </head>
    <body>
    <form action="" method="">	
    	<div id="cat"><fieldset>			
    			<legend>Categories</legend>			
    			<p>Please enter your categories to build the drop-down list : 
    				<br>(select a categorie in the dropdownlist to remove it).</p>			
    			<table>
    				<tr><td rowspan="2" valign="top">
    						<select id="catLst" onclick="removeCat(this.selectedIndex)" title="Click me to remove a categorie !">
    							<option>Categories
    							</option>
    						</select></td>
    					<td>
    						<input type="text" id="newCat" value="New categorie" onfocus="rmvDfl(this)">&nbsp; 				
    						<input type="button" onclick="addCat()" value="Enter !">
    						</td>
    				</tr>
    				<tr><td align="right" valign="bottom"><input type="button" onclick="endCat()" value="Valid this list !"></td>
    				</tr>			
    			</table>		
    	</fieldset></div>	
    	<div id="itm" class="dsb"><fieldset>			
    			<legend>Items 			
    			</legend>Please list your items and choose your categories for them:<br />			
    			<input type="text" id="newItm" value="" disabled="disabled">           			 		
    	</fieldset></div>
    </form>
    <script type="text/javascript">
    function $(id) {return document.getElementById(id);
    }
    function rmvDfl(t){
    	if (t.value==t.defaultValue) {t.value="";if (document.selection && document.selection.clear) document.selection.clear();}
    }
    function addCat(){var objCat=$('newCat');
    	if (objCat.value=='') objCat.value=objCat.defaultValue;
    	else if (objCat.value!=objCat.defaultValue) {var objLst=$('catLst');
    		objLst.options[objLst.options.length]=new Option(objCat.value,objCat.value);
    		objLst.size=objLst.options.length;
    		objCat.value=objCat.defaultValue;}
    }
    function removeCat(n){var objLst=$('catLst');
    	if (n) {objLst.options[n]=null;objLst.size=objLst.options.length;}
    }
    function endCat(){
    	$('itm').className='act';
    	var slc=$('catLst').cloneNode(true);
    	slc.title="Choose a cathegorie to valid this item !";
    	slc.onclick=null; // to complete with a new fonction 
    	$('cat').parentNode.removeChild($('cat'));
    	// to avoid carraige returns, tabs or other comments ant to get the first &#171;right&#187; node (the fieldset)
    	j=0;while ($('itm').childNodes[j].nodeType!=1) j++
    	$('itm').childNodes[j].appendChild(slc);
    	$('newItm').disabled=false;
    }
    </script>
    </body>
    </html>
    Last edited by 007Julien; 07-24-2012 at 04:38 PM.

  5. #5
    Join Date
    Jul 2012
    Posts
    10
    Again 007Julien, I appreciate the time and help you're providing. The code you've provided is a bit advanced for me and I'm having a hard time understanding it. I added that code and it has a partial working layout, but not completely.

    After going over the tutorials several times in W3, I was able to piece this together. Keep in mind I am a n00b and this code could definitely be condensed, but it does what I need it too. Maybe we could look at this as the foundation and work from there (I did notice you tried adding some additional functionality with add/remove capability).

    In the head I have 2 functions - 1 to update the data and 1 to simply display/submit it later on
    Code:
    <script type="text/javascript">
    <!--
    
    
    function upOpts() { //update cat options
      var d=document;
      var A=d.getElementById("cat1").value; // gets 1st category
      var B=d.getElementById("cat2").value; // gets 2nd category
      var C=d.getElementById("cat3").value; // gets 3rd category
    
      // setup options from list of categories
      var showOpts="<option>"+A+"</option>"
    	+"<option>"+B+"</option>"
    	+"<option>"+C+"</option>";
    
      // add recently added options to form in 2nd section (items)
      document.getElementById("target1").innerHTML="<select id=\"o1\">" + showOpts + "</select>";
      document.getElementById("target2").innerHTML="<select id=\"o2\">" + showOpts + "</select>";
      document.getElementById("target3").innerHTML="<select id=\"o3\">" + showOpts + "</select>";
    }
    
    
    
    
    function showResults() {  // show options
      var d=document;
      var A1=d.getElementById("o1").value; // chosen cat
      var A2=d.getElementById("itm1").value; // item
    
      var B1=d.getElementById("o2").value; // chosen cat
      var B2=d.getElementById("itm2").value; // item
    
      var C1=d.getElementById("o3").value; // chosen cat
      var C2=d.getElementById("itm3").value; // item
    
      document.getElementById("showR").innerHTML=""
    	+ "Item 1: <b>" + A2 + "</b>, Category: <b>" + A1 + "</b><br />"
    	+ "Item 2: <b>" + B2 + "</b>, Category: <b>" + B1 + "</b><br />"
    	+ "Item 3: <b>" + C2 + "</b>, Category: <b>" + C1 + "</b><br />";
    }
    
    
    //-->
    </script>
    In the body, I have my Category section and Item section
    For this section (if you test it), you'll notice that when a value is typed into category, it populates the dropdown in the item section as soon as the user leaves the category input box.
    HTML Code:
    <!-- SECTION: Categories - section to grab data from -->
    
    <div style="width: 400px"><fieldset><legend>Categories</legend>
    
    1.<input type="text" id="cat1" onblur="upOpts()"><br />
    2.<input type="text" id="cat2" onblur="upOpts()"><br />
    3.<input type="text" id="cat3" onblur="upOpts()">
    
    </fieldset></div>
    
    <br />
    
    <!-- SECTION: Items - placeholder and also where data grabbed will be placed -->
    
    
    
    <div style="width: 400px"><fieldset><legend>Items</legend>
    
    1.<input type="text" id="itm1"><span id="target1"><select><option>No Options 
    
    Yet</option></select></span><br />
    2.<input type="text" id="itm2"><span id="target2"><select><option>No Options 
    
    Yet</option></select></span><br />
    3.<input type="text" id="itm3"><span id="target3"><select><option>No Options 
    
    Yet</option></select></span>
    
    </fieldset></div>
    
    
    
    <p id="showR"></p>
    <button onclick="showResults()">Results</button>
    I'm wondering if I can simplify this using an array option.
    Last edited by silenced1; 07-25-2012 at 02:09 PM.

  6. #6
    Join Date
    Jul 2012
    Posts
    3
    If I understand your requirements correctly ( you want to populate a select based on values entered in textboxes ), you are making this far more complicated than need be:

    The following code does what you are looking for. It can be shortened using jQuery or YUI if you prefer. Note it fires on the change event, which is unreliable and requires you to click elsewhere before the event fires, you may want to change that to possibly onKeyUp or something similar.


    HTML Code:
    <html>
    <head>
     <script>
     function addToCombo()
     {
      document.getElementById('select1').options.add(
      new Option(document.getElementById('nameCat').value,document.getElementById('nameCat').value));
     }
     </script>
    </head>
    <body>
     <form>
    
     <input type=text id=nameCat onchange="addToCombo()" ></input>
     <br />
     <select id=select1>
      <option>1</option>
      <option>2</option>
      <option>3</option>
     </select>
     </form>
    </body>
    </html>

  7. #7
    Join Date
    Jul 2012
    Posts
    10
    Quote Originally Posted by Serapth View Post
    If I understand your requirements correctly ( you want to populate a select based on values entered in textboxes ), you are making this far more complicated than need be:

    The following code does what you are looking for. It can be shortened using jQuery or YUI if you prefer. Note it fires on the change event, which is unreliable and requires you to click elsewhere before the event fires, you may want to change that to possibly onKeyUp or something similar.
    Hello Serapth. Trust me... I (as a n00b) understand I'm making this more complicated then it needs to be, but I'm learning all of the time

    As for your script, I definitely love the simplicity of it, but it doesn't compensate for changing the department values if needed.

    Once this form (which is MUCH longer then I'm showing you guys) is complete, there will be several different types of 'Categories' and when people add items and need to change any of that data, all they have to do at the moment is update the category name info (with possible reselection for the item itself).

    As for jQuery and YUI is concerned, they look like decent libraries, but I'm not sure if I'm ready for them just yet until I get over the basics of javascript. Even though I'm making this for work, this is still a learning experience that I'm absorbing.

    In any case, I'll see what I can do with the knowledge you've added and I appreciate the help

  8. #8
    Join Date
    Jul 2012
    Posts
    10
    @Serapth: You were right, mines very complex and I noticed that when I update a category it changes all of the values for the items to the first option, which would be a pain for the end-user when they have to add/update categories after they've added a bunch of items.

    I started looking back at your function (which is very simplified - I like), but I noticed that when I hit the ENTER key, it wipes out the values as well. If I tab out of the field, then it adds the options.

    Is there any way I can utilize an array in this type of fasion?
    Code:
    // "sudo-code" really: THIS EXAMPLE IS A FAILURE and is just examples of the intension
    
    // First I'd have this kind of possible setup to pull from:
    <input type="text" name="thisCat">
    <input type="text" name="thisCat">
    
    // Then with that in mind, could I build an array saying something like:
    var cats = document.getElementsByTagName("thisCat").text;
    var catList = new Array(cats);
    
    // And have the options listed with:
    function someFunc {
      document.getElementById('Opts').innerHTML="<option>" + catList + "<\/option>"
    }
    
    <select onclick="someFunc" id="Opts">
      <option>[Choose Category]</option>
    </select>
    I know at some point I need to shove a loop in their to repeat the options list (I think). I have a hard time piecing this together in my mind to make things connect and I think part of it is the loops and how to get the options listed (I'm also still trying some stuff with the originally provided snippet from Serapth).

  9. #9
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,270
    Read this page to learn how to change select element content on the fly... The second proposed script uses simply this methods !
    Last edited by 007Julien; 07-30-2012 at 05:46 PM.

  10. #10
    Join Date
    Jul 2012
    Location
    UK
    Posts
    15
    Hi There, try my solution... I hope this is kinda what your looking for...

    html:
    HTML Code:
    <form action="" method="">
    
    <h3>Section 1:</h3>
    
    Please list your categories:<br />
    Cat 1: <input type="text" name="cat1Nam" value="" class="cat"><br />
    Cat 2: <input type="text" name="cat2Nam" value="" class="cat"><br />
    Cat 3: <input type="text" name="cat3Nam" value="" class="cat"><br />
    Cat 4: <input type="text" name="cat4Nam" value="" class="cat"><br />
    
    
    
    <h3>Section 2:</h3>
    
    Please list your items and choose your categories for them:<br />
    
    Item 1: <input type="text" name="itm1Nam" value="">
            <select name="itm1list" onClick=""></select>
    <br />
    
    Item 2: <input type="text" name="itm2Nam" value="">
            <select name="itm2list" onClick=""></select>
    <br />
    
    Item 3: <input type="text" name="itm3Nam" value="">
            <select name="itm2list" onClick=""></select>
    
    <br />
    <br />
    <br />
    
    <input type="submit" value="Submit" />
    
    
    </form>
    and the javascript:
    Code:
    <script>
    function setListeners(){
    var doc = document.getElementsByClassName('cat');
    
    for(i=0; i<doc.length; i++){
    doc[i].addEventListener('change', function(){
    				getValues();
    		}, false);
    	}
    }
    
    function getValues(){
    
    var inputs = document.getElementsByClassName('cat');
    var selectItems = document.getElementsByTagName('select');
    var myOptions = new Array;
    
    for(i=0; i<inputs.length; i++)
    			myOptions.push(inputs[i].value);
    
    			
    	for(i=0; i<selectItems.length; i++){
    		selectItems[i].innerHTML = "";
    		
    		for(a=0; a<myOptions.length; a++){
    		
    		var current = selectItems[i].innerHTML;
    		selectItems[i].innerHTML = current + '  <option value="' + myOptions[a] + '">' + myOptions[a] + '</option>';
    	}
    }
    }
    
     window.onload = function(){
    	setListeners();
      }
    </script>
    The code populates the select boxes automatically whenever someone makes a change to one of the categories. If theres anything you'd like me to try and change ill help best I can

  11. #11
    Join Date
    Jul 2012
    Posts
    10
    Hi xxxfirehazrd. That's awesome. I can look at it an understand what's going on with what you provided and it's not as archaic as my version lol.

    So you've made a script that mimics the other, but then it ran into the same issue I ran into. Here's what I did:
    * Fill in categories
    * Fill in items and pick random categories
    * I then think to myself, I need to change that 1 category to something else
    * Go back to change category 2

    Result: Causes all categories in the drop downs to reset back to option 1 (or array[0]) after it updates.

    Issue: If the end user has to change 1 out of 20 to 40 categories after they've already began adding items and setting those categories for the items, if it resets all of the work they did, they're going to feel that the form isn't working with them.

    I wonder if there's a way to say, 'if that category is not a selected option in select tag of items, keep current state'. (I'm totally lost on that one... *shrug*)

    ((And Thanks again... the reconstruction of this is pretty kewl and I hope I can reach that level of competency at some point and then maybe catch up to these others guys with the wild functions. I really appreciate it.))

  12. #12
    Join Date
    Jul 2012
    Posts
    10
    After looking over this and the options available, is there any way we can set the chosen value as having a value of 'Default' within selectedItem set to TRUE per item on an update (or maybe, onChange)? Not sure if we can treat the dropdown options as separate entities like that though.

  13. #13
    Join Date
    Jul 2012
    Posts
    10

    Thumbs up

    Quote Originally Posted by 007Julien View Post
    Read this page to learn how to change select element content on the fly... The second proposed script uses simply this methods !
    By the way: Thanks 007Julien... very useful information here as well... just trying to get the wrinkles ironed out at this point

  14. #14
    Join Date
    Jul 2012
    Location
    UK
    Posts
    15

    Made some changes

    I've made some changes to the code so it maintains unchanged values. Ive also added a default value for each box as you requested

    The one minor issue I have is say a user chose 'randomval' from the dropdown box, and went to change it in the categories, all the selected items that have been selected as 'randomval' will change to default. However, the others stay the same.

    Heres the updated code:
    HTML Code:
    <form action="" method="">
    
    <h3>Section 1:</h3>
    
    Please list your categories:<br />
    Cat 1: <input type="text" name="cat1Nam" value="" class="cat"><br />
    Cat 2: <input type="text" name="cat2Nam" value="" class="cat"><br />
    Cat 3: <input type="text" name="cat3Nam" value="" class="cat"><br />
    Cat 4: <input type="text" name="cat4Nam" value="" class="cat"><br />
    Cat 5: <input type="text" name="cat4Nam" value="" class="cat"><br />
    
    
    <h3>Section 2:</h3>
    
    Please list your items and choose your categories for them:<br />
    
    Item 1: <input type="text" name="itm1Nam" value="">
            <select name="itm1list" onClick="">
    			<option value="default" class="myItems">- Please select a category -</option>
    		</select>
    <br />
    
    Item 2: <input type="text" name="itm2Nam" value="">
            <select name="itm2list" onClick="">
    			<option value="default" class="myItems">- Please select a category -</option>
    		</select>
    <br />
    
    Item 3: <input type="text" name="itm3Nam" value="">
            <select name="itm2list" onClick="">
    			<option value="default" class="myItems">- Please select a category -</option>
    		</select>
    
    <br />
    <br />
    <br />
    
    <input type="submit" value="Submit" />
    
    
    </form>
    Javascript:
    Code:
    <script>
    var run = false;
    
    function setListeners(){
    var doc = document.getElementsByClassName('cat');
    
    for(i=0; i<doc.length; i++){
    doc[i].addEventListener('change', function(){
    				getValues();
    		}, false);
    	}
    }
    
    function getValues(){
    
    //Initialise variables.
    var inputs = document.getElementsByClassName('cat');
    var selectItems = document.getElementsByTagName('select');
    var options = document.getElementsByClassName('myItems');
    var myCurrentValues = new Array();
    var myOptions = new Array();
    
    
    if(run){
    	//Push current option values to 'myCurrentValues' array.
    	for(c=0; c< selectItems.length; c++){
    		myCurrentValues.push(selectItems[c].options[selectItems[c].selectedIndex].value);
    	}
    }
    
    //Push category values to array called 'myOptions'.
    for(i=0; i<inputs.length; i++)
    	myOptions.push(inputs[i].value);
    			
    	for(i=0; i<selectItems.length; i++){
    	selectItems[i].innerHTML = '<option value="default" class="myItems">- Please select a category -</option>';
    		
    		//Populate select items with options.
    		for(a=0; a<myOptions.length; a++){
    			var current = selectItems[i].innerHTML;
    			selectItems[i].innerHTML = current + '  <option value="' + myOptions[a] + '" class="myItems">' + myOptions[a] + '</option>';
    		}
    	}
    	
    	//Automatically select last current values before change.
    	for(i=0; i<selectItems.length; i++){
    			var myarray = new Array();
    			var holder = selectItems[i].getElementsByClassName('myItems');
    			
    			for(a=0; a<holder.length; a++)
    			myarray.push(holder[a].value);
    		
    			var b = myarray.indexOf(myCurrentValues[i]);
    			if(b!== -1)
    			holder[b].selected=true;
    			
    			else
    			continue;
    	}
    	
    run = true;
    }
    
    window.onload = function(){
    	setListeners();
      }
    </script>

  15. #15
    Join Date
    Jul 2012
    Location
    UK
    Posts
    15

    *edit

    Whilst debugging, I noticed a compatability issue with IE. Apparently, IE doesn't like .innerHTML very much, and so the options wouldn't populate.

    I've decided to create the elements using the .createElement method instead as a result. Ive also condensed the code by taking out the eventListeners (another IE issue) and attached an onChange attribute to the category input fields within the form.

    Here's the updated code...

    HTML Code:
    <form action="#">
    
    <h3>Section 1:</h3>
    
    Please list your categories:<br />
    <input type="hidden" name="default" value=" - Please Select A Category - " class="cat"/>
    Cat 1: <input type="text" name="cat1Nam" value="" onChange="javascript: getValues();" class="cat"><br />
    Cat 2: <input type="text" name="cat2Nam" value="" onChange="javascript: getValues();" class="cat"><br />
    Cat 3: <input type="text" name="cat3Nam" value="" onChange="javascript: getValues();" class="cat"><br />
    Cat 4: <input type="text" name="cat4Nam" value="" onChange="javascript: getValues();" class="cat"><br />
    Cat 5: <input type="text" name="cat4Nam" value="" onChange="javascript: getValues();" class="cat"><br />
    
    
    <h3>Section 2:</h3>
    
    Please list your items and choose your categories for them:<br />
    
    Item 1: <input type="text" name="itm1Nam" value="">
            <select name="itm1list" onClick="">
    			<option value="default" class="myItems">- Please Select A Category -</option>
    		</select>
    <br />
    
    Item 2: <input type="text" name="itm2Nam" value="">
            <select name="itm2list" onClick="">
    			<option value="default" class="myItems">- Please Select A Category -</option>
    		</select>
    <br />
    
    Item 3: <input type="text" name="itm3Nam" value="">
            <select name="itm2list" onClick="">
    			<option value="default" class="myItems">- Please Select A Category -</option>
    		</select>
    
    <br />
    <br />
    <br />
    
    <input type="submit" value="Submit" />
    
    
    </form>
    JAVASCRIPT:
    Code:
    <script type="text/javascript">
    var run = false;
    
    function getValues(){
    
    //Initialise variables.
    var inputs = document.getElementsByClassName('cat');
    var selectItems = document.getElementsByTagName('select');
    var options = document.getElementsByClassName('myItems');
    var myCurrentValues = new Array();
    var myOptions = new Array();
    
    
    if (run){
    	//Push current option values to 'myCurrentValues' array.
    	for (c=0; c< selectItems.length; c++){
    		myCurrentValues.push(selectItems[c].options[selectItems[c].selectedIndex].value);
    	}
    }
    
    //Push category values to array called 'myOptions'.
    for (i=0; i<inputs.length; i++)
    	myOptions.push(inputs[i].value);
    			
    	for (i=0; i<selectItems.length; i++){
    		selectItems[i].innerHTML = '';
    	
    		//Populate select items with options.
    		for (a=0; a<myOptions.length; a++){
    		var myElm = document.createElement('Option');
    		myElm.text = myOptions[a];
    		myElm.value = myOptions[a];
    		myElm.setAttribute('class', 'myItems');
    		selectItems[i].appendChild(myElm);
    		}
    	}
    	
    	//Automatically select last current values before change.
    	for (i=0; i<selectItems.length; i++){
    			var myarray = new Array();
    			var holder = selectItems[i].getElementsByClassName('myItems');
    			
    			for (a=0; a<holder.length; a++)
    			myarray.push(holder[a].value);
    		
    			var b = myarray.indexOf(myCurrentValues[i]);
    			if (b!== -1)
    			holder[b].selected=true;
    			
    			else
    			continue;
    	}
    	
    run = true;
    }
    </script>

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles