2011-05-10 243 views
1

我想將所選的選項更改爲另一個值。 即,更改選擇選項選擇

<select id="myid"> 
<option value="1" selected="selected">1 </option> 
<option value="2" >2 </option> 
<option value="3" >3 </option> 
<option value="4" >4 </option> 
</select> 

我要觸發這個選擇的變化,選擇第三選項,我有我怎麼能做到這一點的價值?

我每次都添加一個選項的功能,我希望每次添加選項後,我都希望它被選中做進一步的活動。

回答

2

若要更改索引

<input type="button" value="Change Select" onclick="changeSelect(3)" /> 

function changeSelect(x) { 
    document.frm.myid.selectedIndex = x-1; 
} 

通過數值來改變

<input type="button" value="Change Select" onclick="changeSelect1(3)" /> 

function changeSelect1(x) { 
    var myid = document.getElementById('myid'); 
    var st = myid.options; 
    for(var i=0; i<st.length; i++) { 
    if(st[i].value == x) { 
     myid.selectedIndex = i; 
    } 
    } 
} 

+0

我可以通過傳遞選項值來改變jquery觸發器函數嗎? – Devan 2011-05-10 09:27:38

+1

是的,當然。請參閱鏈接http://stackoverflow.com/questions/496052/jquery-setting-the-selected-value-of-a-select-control-via-its-text-description – 2011-05-10 10:38:50

0

選擇=「選擇」,選擇您想要的選項,只是把它放在第三選項標籤

例如

<select id="myid"> 
    <option value="1">1 </option> 
    <option value="2">2 </option> 
    <option value="3" selected="selected">3 </option> 
    <option value="4">4 </option> 
</select> 
+0

實際上,我每次都添加一個選項我希望它被選中。你展示的方式是不可能的 – Devan 2011-05-10 09:29:46

1
function Change() { 
      for (i = 0; i < document.getElementById('ddStream').options.length; i++) { 
       if (document.getElementById('ddStream').options[i].value == 1) 
       document.getElementById('ddStream').selectedIndex = i; 
      } 
      alert(document.getElementById('ddStream').selectedIndex); 
      return false; 
     } 

<select id="ddStream" onchange="return Change()"> 
          <option value="">EEE</option> 
          <option value="">ECE</option> 
          <option value="">CSE</option> 
          <option value="1">E&I</option> 
         </select> 

這是最基本的語法..你提到將通過邏輯去你所寫的..如其他事情,以選擇ü動態添加, 的document.getElementById最後一個選項( 'ddStream')。selectedIndex = document.getElementById('ddStream')。options.length -1