简体   繁体   English

无法使用javascript在下拉菜单中设置值

[英]Unable to set a value in the drop down using javascript

i am having trouble selecting an element from a drop down box. 我无法从下拉框中选择元素。 Here is the div 这是div

<div class="select ccMonth" id="payflow-form-ccMonth-select">
<select name="expMonth" class="month payflow-form-ccMonth-select   hidden" id="payflow-form-ccMonth-select-select">
<option value="Month">Month</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<span name="expirationMonthSpan">Month</span><ul>
<li data-index="0">Month</li>
<li data-index="1">1</li>
<li data-index="2">2</li>
</ul>
</div>

The div is returned correctly when i run this 当我运行这个div正确返回

document.getElementById('payflow-form-ccMonth-select-select');

However on Chrome when i try the below, it doesn't set value i want in the drop down box. 但是,当我尝试以下操作时,在Chrome上,它没有在下拉框中设置我想要的值。

document.getElementById('payflow-form-ccMonth-select-select').selectedIndex=1;

I have also tried to get it in focus first with click() which expands the drop down box but it still won't work. 我还尝试过首先使用click()使其聚焦,该方法扩展了下拉框,但仍然无法正常工作。

document.getElementById('payflow-form-ccMonth-select-select').click();
document.getElementById('payflow-form-ccMonth-select-select').selectedIndex=1;

I have also tried this which did not work either 我也尝试过这个也没有用

document.getElementById('payflow-form-ccMonth-select-select').value = 1;

Any hints on what i may be missing? 关于我可能会缺少什么的任何提示? Thanks 谢谢

Try: 尝试:

  var dropdown = document.getElementById('payflow-form-ccMonth-select-select');
  dropdown.options[indexToSelect].selected = true;

I have checked your Code and its working Fine Check This . 我检查你的代码和它的工作精细检查

The only Problem I can think is that your code is placed in head and it get executed before actual page is ready 我能想到的唯一问题是,您的代码放在了head并且在实际页面准备好之前就执行了

you can try window.onload 你可以尝试window.onload

window.onload = function(){
   document.getElementById('payflow-form-ccMonth-select-select').selectedIndex= 1;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM