2017-05-07 20 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

相关问题