Upv*_*ote 337 html jquery html-select jquery-selectors
我想设置一个先前选择的选项,以便在页面加载时显示.我用以下代码尝试了它:
$("#gate").val('Gateway 2');
Run Code Online (Sandbox Code Playgroud)
同
<select id="gate">
<option value='null'>- choose -</option>
<option value='gateway_1'>Gateway 1</option>
<option value='gateway_2'>Gateway 2</option>
</select>
Run Code Online (Sandbox Code Playgroud)
但这不起作用.有任何想法吗?
Dar*_*rov 478
这肯定应该工作.这是一个演示.确保已将代码放入$(document).ready:
$(function() {
$("#gate").val('gateway_2');
});
Run Code Online (Sandbox Code Playgroud)
Zko*_*koh 157
$(document).ready(function() {
$("#gate option[value='Gateway 2']").prop('selected', true);
// you need to specify id of combo to set right combo, if more than one combo
});
Run Code Online (Sandbox Code Playgroud)
小智 36
$('#gate').val('Gateway 2').prop('selected', true);
小智 15
我发现使用jQuery .val()方法有一个明显的缺点.
<select id="gate"></select>
$("#gate").val("Gateway 2");
Run Code Online (Sandbox Code Playgroud)
如果此选择框(或任何其他输入对象)在表单中并且表单中使用了重置按钮,则单击重置按钮时,设置值将被清除,并且不会像您期望的那样重置为开始值.
这似乎对我来说是最好的.
对于选择框
<select id="gate"></select>
$("#gate option[value='Gateway 2']").attr("selected", true);
Run Code Online (Sandbox Code Playgroud)
用于文本输入
<input type="text" id="gate" />
$("#gate").attr("value", "your desired value")
Run Code Online (Sandbox Code Playgroud)
对于textarea输入
<textarea id="gate"></textarea>
$("#gate").html("your desired value")
Run Code Online (Sandbox Code Playgroud)
对于复选框
<input type="checkbox" id="gate" />
$("#gate option[value='Gateway 2']").attr("checked", true);
Run Code Online (Sandbox Code Playgroud)
对于单选按钮
<input type="radio" id="gate" value="this"/> or <input type="radio" id="gate" value="that"/>
$("#gate[value='this']").attr("checked", true);
Run Code Online (Sandbox Code Playgroud)
Moh*_*hir 12
$("#form-field").val("5").trigger("change");
Run Code Online (Sandbox Code Playgroud)
这很好.看到这个小提琴:http://jsfiddle.net/kveAL/
您可能需要在$(document).ready()处理程序中声明您的jQuery 吗?
另外,你可能有两个具有相同ID的元素吗?
小智 6
我有同样的问题。
解决方法:添加刷新。
$("#gate").val('Gateway 2');
$("#gate").selectmenu('refresh');
Run Code Online (Sandbox Code Playgroud)
这将是另一种选择:
$('.id_100 option[value=val2]').prop('selected', true);
Run Code Online (Sandbox Code Playgroud)