设置select框的选定选项

我想设置一个以前select的选项,以在页面加载时显示。 我试着用下面的代码:

$("#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> 

但是这不起作用。 有任何想法吗?

这绝对应该工作。 这是一个演示 。 确保你已经把你的代码放到$(document).ready

 $(function() { $("#gate").val('Gateway 2'); }); 
 $(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 }); 

$('#gate').val('Gateway 2').prop('selected', true);

我发现使用jQuery .val()方法有一个显着的缺点。

 <select id="gate"></select> $("#gate").val("Gateway 2"); 

如果此select框(或任何其他input对象)处于窗体中,并且表单中使用了重置button,则单击重置button时,设置值将被清除,而不会像您期望的那样重置为开始值。

这似乎对我来说是最好的。

对于select框

 <select id="gate"></select> $("#gate option[value='Gateway 2']").attr("selected", true); 

用于文本input

 <input type="text" id="gate" /> $("#gate").attr("value", "your desired value") 

对于textareainput

 <textarea id="gate"></textarea> $("#gate").html("your desired value") 

对于checkbox

 <input type="checkbox" id="gate" /> $("#gate option[value='Gateway 2']").attr("checked", true); 

对于单选button

 <input type="radio" id="gate" value="this"/> or <input type="radio" id="gate" value="that"/> $("#gate[value='this']").attr("checked", true); 

这工作正常。 看到这个小提琴: http : //jsfiddle.net/kveAL/

您可能需要在$(document).ready()处理程序中声明您的jQuery?

另外,你可能有两个具有相同ID的元素?

  $("#form-field").val("5").trigger("change"); 

这将是另一个select:

 $('.id_100 option[value=val2]').prop('selected', true); 
 $(function() { $("#demo").val('hello'); }); 

我的问题

 get_courses(); //// To load the course list $("#course").val(course); //// Setting default value of the list 

我遇到过同样的问题 。 与你的代码的唯一区别是,我通过ajax调用加载select框,并且在执行ajax调用时,我已经设置了select框的默认值

解决scheme

 get_courses(); setTimeout(function() { $("#course").val(course); }, 10); 

我有同样的问题。

解决scheme:添加一个刷新。

 $("#gate").val('Gateway 2'); $("#gate").selectmenu('refresh'); 

我有一个问题,因为在调用之前的语法错误,没有设置值。

 $("#someId").value(33); //script bailed here without showing any errors Note: .value instead of .val $("#gate").val('Gateway 2'); //this line didn't work. 

在调用之前检查语法错误。

 // Make option have a "selected" attribute using jQuery var yourValue = "Gateway 2"; $("#gate").find('option').each(function( i, opt ) { if( opt.value === yourValue ) $(opt).attr('selected', 'selected'); }); 

除了@icksde和@Korah(thx两个!)

在使用AJAX构build选项时可能会在构build列表之前触发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"); });