使用jQuery设置按选项选择值 [英] Setting a select by option value using jQuery
本文介绍了使用jQuery设置按选项选择值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的代码:
<body>
<div id="players" style="display:block">
22
</div>
<select class="form-control playerDD" style="font-weight: normal" name="player_1" id="player_1">
<option value="default">Select a player</option>
<optgroup label="Available Players">
<option value="22">John Smith</option>
<option value="23">Jane Smith</option>
<option value="24">Sam Smith</option>
</optgroup>
<optgroup label="Unavailable Players">
<option value="25">John Smith 2</option>
<option value="26">Jane Smith 2</option>
<option value="27">Sam Smith 2</option>
</optgroup>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var foo = $("#players").text();
alert(foo); // Getting the right value and type
//foo = "22"; // This will work!
$("#player_1").val(foo); // Does not work
alert($('#player_1').val()); // Getting null
</script>
</body>
问题::我正在尝试基于div(id:玩家)中的值设置下拉列表(id:玩家_1)的值.我能够正确读取该值,但无法设置它.在JavaScript中,如果我对foo的值进行硬编码,它就可以工作!
Problem: I am trying to set the value of a drop-down list (id: player_1) based on the value in a div (id: players). I am able to read the value correctly but unable to set it. In the JavaScript, if I hard code the value of foo, it works!
这是jsfiddle: https://jsfiddle.net/4w1ack9f/2/ >
Here is the jsfiddle: https://jsfiddle.net/4w1ack9f/2/
推荐答案
$( document ).ready(function() {
$('#player_1').val(parseInt($('#players').text()));
});
这篇关于使用jQuery设置按选项选择值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文