我想设置一个选项,之前选择显示在页面加载。我尝试了下面的代码:

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

with

<select id="gate">
    <option value='null'>- choose -</option>
    <option value='gateway_1'>Gateway 1</option>
    <option value='gateway_2'>Gateway 2</option>
</select>

但这并不奏效。什么好主意吗?


当前回答

// 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');
});

其他回答

我也有同样的问题。

解决方法:添加刷新。

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

有些情况可能是

$('#gate option[value='+data.Gateway2+']').attr('selected', true);

我的问题

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

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

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

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