views:

543

answers:

4
  • Here have two list field menu. First brand second item
  • I want if we select brand IBM that item will select IBM too
  • In other hand, if we select brand HP that item will select HP too

How to do that in javascript.

<select name="brand">
  <option>Please Select</option>
  <option>IBM</option>
  <option>HP</option>
</select>

<select name="item">
  <option>Please Select</option>
  <option>IBM</option>
  <option>HP</option>  
</select>
+2  A: 
 <select name="brand" id="brand" onchange="document.getElementById('item').value = document.getElementById('brand').value">
   <option>Please Select</option>
   <option>IBM</option>
   <option>HP</option>
 </select>

 <select name="item" id="item">
   <option>Please Select</option>
   <option>IBM</option>
   <option>HP</option>  
 </select>
Alsciende
+1  A: 

I noticed your options line up with one another, so you could simply reflect the selectedIndex in in the second from the first:

document.getElementById("brand").onchange = function(){
  document.getElementById("item").selectedIndex = this.selectedIndex;
}
Jonathan Sampson
+1  A: 

You can add an onchange attribute to your brand select element. When a brand is selected, then the selectItem function will be called, which in turn can select the item that matches the value in the item select element. Also, I recommend that you give IDs to your select elements so that you can use document.getElementById("brand").

<select id="brand" name="brand" onchange="selectItem(this.selectedIndex);">
  <option>Please Select</option>
  <option>IBM</option>
  <option>HP</option>
</select>

Here is the DOM reference for the select element: http://www.w3schools.com/jsref/dom_obj_select.asp

hoffmandirt
A: 

What if I want to do the same but changing more than 1 select at the same time: So, I have got the main select:

<select name="brand" id="brand" onchange="document.getElementById('item').value = document.getElementById('brand').value">
  <option>Please Select</option>
  <option>IBM</option>
  <option>HP</option>
</select>

And the next selects are made in php with a loop, so I will have 3,4,5,... selects depending the situation

<select name=item_".$itemnumber." id="item">
 <option>Please Select</option>
 <option>IBM</option>
 <option>HP</option>  
</select>

With this I want to have the possibility to select in one time the option for all the selects, and dont go in each of the selects one by one.

pepersview