我想设置一个之前被选中的选项,在页面加载时显示。我试着用下面的代码。
$("#gate").val('Gateway 2');
与
<select id="gate">
<option value='null'>- choose -</option>
<option value='gateway_1'>Gateway 1</option>
<option value='gateway_2'>Gateway 2</option>
</select>
但这并不奏效。有什么想法吗?
这肯定会起作用。[这里有一个演示][1]。确保你已经把你的代码放在了$(document).ready
中。
$(function() {
$("#gate").val('gateway_2');
});
$('#gate').val('Gateway 2').prop('selected', true);
。
我发现使用jQuery .val()方法有一个很大的缺点。
<select id="gate"></select>
$("#gate").val("Gateway 2");
如果这个选择框(或任何其他输入对象)在一个表单中,并且在表单中使用了复位按钮,当点击复位按钮时,设置值将被清除,而不是像你所期望的那样复位到初始值。
这似乎对我来说是最好的。
对于选择框
<select id="gate"></select>
$("#gate option[value='Gateway 2']").attr("selected", true);
用于文本输入
<input type="text" id="gate" />
$("#gate").attr("value", "your desired value")
对于文字区域的输入
<textarea id="gate"></textarea>
$("#gate").html("your desired value")
对于复选框
<input type="checkbox" id="gate" />
$("#gate option[value='Gateway 2']").attr("checked", true);
对于单选按钮
<input type="radio" id="gate" value="this"/> or <input type="radio" id="gate" value="that"/>
$("#gate[value='this']").attr("checked", true);
我知道有好几个答案的迭代,但现在这不需要jquery或任何其他外部库,只需用下面的方法就可以很容易地完成。
<!--开始片段。 js hide: false console.true babel: true true babel.false --> -- begin snippet: js hide: false console: true false -->
document.querySelector("#gate option[value='Gateway 2']").setAttribute('selected',true);
<select id="gate">
<option value='null'>- choose -</option>
<option value='Gateway 1'>Gateway 1</option>
<option value='Gateway 2'>Gateway 2</option>
</select>
<!--结束片段-->
我的问题
get_courses(); //// To load the course list
$("#course").val(course); //// Setting default value of the list
我也有同样的问题。 与你的代码唯一不同的是,我是通过ajax调用加载选择框,一旦ajax调用被执行,我已经设置了选择框的默认值。
解决方案
get_courses();
setTimeout(function() {
$("#course").val(course);
}, 10);
对 @icksde 和 @Korah 的补充 (thx both!)
*当使用AJAX构建选项**时,document.ready可能会在列表构建之前被触发,所以...。
这不工作
$(document).ready(function() {
$("#gate").val('Gateway 2');
});
这就是
超时确实有效,但正如 @icksde 所说,它很脆弱(我实际上需要 20ms 而不是 10ms)。 最好把它放在AJAX函数里面,像这样。
$("#someObject").change(function() {
$.get("website/page.php", {parameters}, function(data) {
$("#gate").append("<option value='Gateway 2'">" + "Gateway 2" + "</option>");
$("#gate").val('Gateway 2');
}, "json");
});