Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Prevent from displaying same choice when choosing from x # of dropdown

Status
Not open for further replies.

lupidus

MIS
Jun 1, 2003
30
US
I have a page where I generate x number of rows each with a dropdown box. Values for the dropdown list and default selected values will be chosen on initial page load for each dropdown.

I want to write some javascript that will make it so there aren't any values that are redisplayed for any dropdown (for example, if on row 1, option #2 is chosen, option #2 shouldn't show up in any other dropdown until its deselected. Similarly, if option #2 is chosen on row 1 and option #3 is chosen on row 2, then option #2 and #3 shouldn't show up on any dropdown list until deselected).

I found some similar code here:
, but it works only for a static number of dropdown boxes and would not be easily expanded to an arbitrary # of dropdowns.

I'm pretty new to javascript still and it seems to be this may be a challenging project to start out with, but any help is greatly appreciated.

Here is some psuedo code of what my html structure is like:

Code:
<form method="post" name="licenseform">
<select name="Select2"> 
		<option value="1">Intended For: Jon Doe -> St. Louis: 1 of 10</option> 
		<option value="2">Test</option>
		...
		<option value="n">test2</option>
		<option selected value="">None</option>  
</select>
....

<select name="SelectN">
Same options as above/below , but don't redisplay any options that are selected above or elsewhere
</select>

The select names are dynamically generated, but this shouldn't matter what they're called as I can iterate among all dropdownlist objects in the form via javascript?
 
something like this?
Code:
<html>
  <head>
    <title>test</title>

    <script type="text/javascript">
      function foo(sel) {
        var opts = sel.options;
        
        if (opts.length > 1) {
          var name = sel.name.split("_")[0];
          var num = parseInt(sel.name.split("_")[1], 10);
          
          //  need to remove all selects after this one
          var remaining = opts.length - 1;
          var first = num + 1;
          var last = first + (remaining - 1);
          
          for (var x = first; x <= last; x++) {
            var selTmp = sel.form.elements[name + "_" + x];
            if (selTmp != null) {
              //  we added the select in a div, so remove it too
              var parent = selTmp.parentNode;
              sel.form.removeChild(parent);
            }
          }
          
          //  now create the next new select
          var div = document.createElement("div");
          var selNew = document.createElement("select");
          
          selNew.name = name + "_" + ++num;
          selNew.onchange = function(){ foo(this); };
          
          for (var x = 0; x < opts.length; x++) {
            if (opts[x] != sel.options[sel.selectedIndex]) {
              var opt = new Option(opts[x].text, opts[x].value);
              selNew.options.add(opt);
            }
          }
          
          //  wrap the select in a div for line break
          div.appendChild(selNew);
          sel.form.appendChild(div);
        }
      }
    </script>

  </head>

  <body>
    <form>
      <div>
        <select name="sel_1" onchange="foo(this);">
        <option value="1">One</option>
        <option value="2">Two</option>
        <option value="3">Three</option>
        <option value="4">Four</option>
        <option value="5">Five</option>
        </select>
      </div>
    </form>
  </body>
</html>

-jeff
try { succeed(); } catch(E) { tryAgain(); } finally { rtfm(); }
i like your sleeves...they're real big
 
Your best bet is to use getElementsByTagName to get hold of all the SELECT tags on the page, then process them checking to see if the first part of the NAME attribute of each element, if there is a match compare the VALUE property of the SELECTEDINDEX against those previously selected, if no match is found, add the VALUE to the previously selected array and then grab the next one. If a match is found then you can error out.
 
jemminger: Thanks,that solution is close to what I need , but it seems your code builds the subsequent select boxes on the fly. In my case, I will intially generate the page with all select boxes already populated, default selections selected, and items eliminated from the select boxes if the item is selected somewhere.

I was working on an easier less elegant solution to my problem (I think I found this code somewhere on tektips). Instead of modifying the contents of the select options, I will validate the page whenever a change is made to a dropdown. No duplicates should be allowed. If a dupe is found, set the current value to selectedindex -1 or the selectedvalue="0"


The issue is that the logic always thinks theres a duplicate entry in another select box and I can't seem to figure out why.

Here is my code:

Code:
var selects;
function grabSelects()
{
 selects = document.getElementsByTagName("SELECT");
 
}

//build a string of the SELECT objects selected indexes.  A duplicate selection will be easily detectable.  An example of a 'valid' indexString would be *2**1**3*.  There are asterisks to both sides of each index as it is added.  This allows for expandability to a number of SELECTs greater than 9.
function compare(obj)
{	
//document.writeln(selects.length);
	var indexString = "";
	var debugString = "";
	var done = 0;
	var idx, val;
	
	var currentIdx=obj.selectedIndex; //the index of the current Option selected
	var currentValue=obj.options[currentIdx].value; //the value of the the current Option.


//	document.writeln(selected_idx);
	//document.writeln(obj.selectedIndex.value);
	//document.writeln(licenseform.obj.options[licenseform.obj.selectedIndex].value);
	if (currentValue != "0") {		// lets check for dupes if the current value of this selectbox is not "None"
		for(var i=0; i<selects.length,done==0; i++)	// chk for dupes on each of the other select boxes
		{
			//idx=selects[i].selectedIndex;		// ok
			//document.writeln(selects[i].value);	// ok
			//if (selects[i].selectedIndex != -1) {
			
				if(selects[i].selectedIndex != -1 && indexString.indexOf("*"+selects[i].selectedIndex+"*") == -1) {
					//if (selects[i].value != 0) {
						indexString += "*"+selects[i].selectedIndex+"*";
					//} 
				
				}
				else if( indexString.indexOf("*"+selects[i].selectedIndex+"*") != -1 )		
				{
				
					alert("You must select a unique value for each dropdown.");
					done=1;
					obj.selectedIndex = -1;
				}
		//	} // if selects[i].selectedindex != -1
		}

	}
	
	
}


			//  End -->
			</script>

	<body class="pageindent" onload='grabSelects();'>
....
<select name="Select1" onchange='compare(this);'><option value="1">text1</option>
<option value="2">text2</option>
....
<option value="n">textn</option>
<option selected value="0">None</option>  </select> 	
...
<select name="SelectN"..............
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top