2017-05-07 21 views
0

所以,我正在嘗試使用Javascript,是因爲當我做類似於document.getElementByID(「產品選擇」)。 它會自動按下給我。Javascript,自動選擇一個下拉菜單

每當我嘗試這樣做時,它會使下拉菜單變爲空白,並且不會自動更改它。我可以得到一些幫助嗎?

<div id="product-variants" class=""> 
    <div class="select-wrapper"> 
    <select id="product-select" name="id" class=""> 




     <option value="28223706565">32</option> 



     <option value="28223706629">34</option> 



     <option value="28223706693">36</option> 


    </select> 
    </div> 
</div> 
+2

的可能的複製[?如何使用JavaScript來改變HTML選定的選項(http://stackoverflow.com/questions/10911526/how-to-change-html-selected-選項使用JavaScript) – YoannM

+0

@YoannM嘿,不,它不是。我試過[圖片錯誤](http://i.imgur.com/tHS6ZVo.png)使用代碼:document.getElementById('product-select')。value = 34; 沒有任何反應 – Bigboymanted

+0

是的,它是... document.getElementByID(「product-select」)。value =「28223706629」;' – brasofilo

回答

2

原因爲何下拉值是不會自動改變是,當你設定降下來價值使用的document.getElementById(「p roduct-select「)value =」34「,它不會選擇文本節點作爲,只有當其中一個選項的值爲34時,纔會更改下拉菜單。爲了使其工作正常改變你的實現,如下所示:

var x = document.getElementById("product-select").options; 
    for(var i=0;i<x.length;i++){ 
     if(x[i].text=="34"){ 
      x[i].selected=true; 
      break; 
    } 
} 
+0

非常感謝你!你已經修好了,我很開心,現在我假設我是否想將它改爲「32」,例如仍然可以工作? – Bigboymanted

+0

是的!如果你想讓它工作一些條件然後把這段代碼放在一個函數中,並在下拉菜單中設置值的參數。 –

+0

嘿,我知道這已經解決了很久以前,但現在這個代碼不起作用?如果我添加我原來的elementgetbyclassname?它說undefined控制檯:( – Bigboymanted

1

也許

document.getElementByID("product-select").value = "34"; 

應該

document.getElementByID("product-select").value = "28223706629"; 

另一種方法是參考指標,如

document.getElementById("product-select").selectedIndex = 1; 
+0

Hey @Tim D 這是selectedIndex仍然發生的錯誤。 [這裏是照片](http://i.imgur.com/Gq5nRDZ.png) – Bigboymanted

0

如果你知道你的價值觀的順序你可以使用

document.getElementByID("product-select").selectedIndex方法

如果要選擇在這種情況下,值34是第二選項,以便它的指數是1,32索引將是0和36指數將是2

所以如果要將該值更改爲34,你叫

document.getElementByID("product-select").selectedIndex = 1

+0

你好。 [這裏是仍然出現的錯誤。](http://i.imgur.com/Gq5nRDZ.png)這就是我的意思selectedIndex不工作:( – Bigboymanted

+0

是的,其實只是.selectedIndex沒有大括號()我的壞 – Quartal

相關問題