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

时间:2017-03-16 04:58:35

标签: javascript

这是我使用的Select标签.. &lt; select class =“form-control”id =“VillagesComboidmod”&gt;   &LT;选项&GT;康提&LT; /选项&GT;   &LT;选项&GT; Ampitiya&LT; /选项&GT;   &LT;选项&GT; Semaneriya&LT; /选项&GT; &LT; /选择&GT; 这是我用来选择值的代码.. document.getElementById('VillagesComboid')。value =“Ampitiya”;

5 个答案:

答案 0 :(得分:2)

您在元素ID的引用中只有一个拼写错误。

设置<select>元素的值

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

应该是

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

此处正在处理JSBin

答案 1 :(得分:0)

使用 ==进行比较。和 =进行作业

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>

请运行以上代码

Here is a working DEMO

答案 2 :(得分:0)

您应该更新您的选择,如下所示:

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

答案 3 :(得分:0)

只需更改您的身份

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

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

答案 4 :(得分:0)

你去吧

<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>