Javascript - How to make auto select another drop down

雨燕双飞 提交于 2020-01-03 02:29:36

问题


  • 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>

回答1:


 <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>



回答2:


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;
}



回答3:


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



来源:https://stackoverflow.com/questions/1974798/javascript-how-to-make-auto-select-another-drop-down

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!