Set selected option of select box

2019-01-03 23:03发布

I want to set a option that was selected previously to be displayed on page load. I tried it with the following code:

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

But this does not work. Any ideas?

14条回答
孤傲高冷的网名
2楼-- · 2019-01-03 23:48

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

查看更多
做自己的国王
3楼-- · 2019-01-03 23:50

This would be another option:

$('.id_100 option[value=val2]').prop('selected', true);
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-01-03 23:55
$(function() {
$("#demo").val('hello');
});
查看更多
老娘就宠你
5楼-- · 2019-01-03 23:56

My problem

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

I had the same issue . The Only difference from your code is that I was loading the select box through an ajax call and soon as the ajax call was executed I had set the default value of the select box

The Solution

get_courses();
   setTimeout(function() {
     $("#course").val(course);
  }, 10);
查看更多
甜甜的少女心
6楼-- · 2019-01-03 23:58

I had a problem where the value was not set because of a syntax error before the call.

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

Check for syntax errors before the call.

查看更多
祖国的老花朵
7楼-- · 2019-01-03 23:59

This definitely should work. Here's a demo. Make sure you have placed your code into a $(document).ready:

$(function() {
    $("#gate").val('Gateway 2');
});
查看更多
登录 后发表回答