简体   繁体   English

如何在中选择一个值 <select>使用javascript标记?

[英]How to Select a value in <select> tag using javascript?

This is the Select tag That I used.. 这是我使用的Select标签。

<select class="form-control" id="VillagesComboidmod">
  <option>Kandy</option>
  <option>Ampitiya</option>
  <option>Semaneriya</option>
</select>

This is the code that I used to select a value.. 这是我用来选择一个值的代码。

document.getElementById('VillagesComboid').value = "Ampitiya";

You've just got a typo in the reference to the element id. 您刚刚在元素ID的引用中出现了错字。

To set the value of the <select> element 设置<select>元素的值

document.getElementById('VillagesComboid').value = "Ampitiya";

should be 应该

document.getElementById('VillagesComboidmod').value = "Ampitiya";

Here it is working on JSBin 在这里,它正在开发JSBin

Use, == , for comparision . ==用于比较 and = for assignment =分配

document.getElementById('VillagesComboid').value == "Ampitiya";

 <!DOCTYPE html> <html> <body> <select class="form-control" id="VillagesComboidmod"> <option>Kandy</option> <option>Ampitiya</option> <option>Semaneriya</option> </select> <button onclick="myFunction()">Try it</button> <script> function myFunction() { alert(document.getElementById("VillagesComboidmod").value == "Ampitiya"); } </script> </body> </html> 

Please run the above CODE 请运行上面的代码

Here is a working DEMO 这是一个有效的演示

You should update your select like below: 您应该像下面这样更新您的选择:

<select class="form-control" id="VillagesComboidmod">
  <option value="Kandy">Kandy</option>
  <option value="Ampitiya">Ampitiya</option>
  <option value="Semaneriya">Semaneriya</option>
</select>

just change your id 只需更改您的ID

document.getElementById('VillagesComboid').value='Ampitiya';

to

document.getElementById('VillagesComboidmod').value='Ampitiya';

Here you go 干得好

<html>
<body>

<p id="demo"></p>

<select class="form-control" id="VillagesComboidmod">
 <option value="K">Kandy</option>
 <option value="A">Ampitiya</option>
 <option value="S">Semaneriya</option>
</select>


<script>
  document.getElementById('VillagesComboidmod').value = 'A';
</script> 

</body>
</html>

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

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