简体   繁体   中英

jQuery set option in dynamic select

I'm using jQuery v1.10.2.

I've a select wich will be filled dynamicly by ajax:

<select id="mySelect"></select>

I'm trying to set an option in a nother ajax call:

function GetValues(id) {
    LoadSelectOptions('#mySelect');
    /* select has now following options:
        <option value="0"></option>
        <option value="1">Test 1</option> */
    $.ajax({
        ..
        success: function (data) {
            $('#mySelect').val(data.value); // data.value = 1
        },
        ..
    });
}

This code $('#mySelect').val(data.value); in my success area of the ajax call don't sets the option to "Test 1". I've also tried to do following:

$('#mySelect').val(data.value).change();
$('#mySelect option[value="' + data.value + '"]').attr('selected', 'selected');
$('#mySelect option[value="' + data.value + '"]').attr('selected', true);
$('#mySelect option[value="' + data.value + '"]').prop('selected', 'selected');
$('#mySelect option[value="' + data.value + '"]').prop('selected', true);

But nothing works in Chrome + Firefox (both latest version).

Thanks for help :)

You can do this :-

$("select#mySelect").val(data.value);

WORKING DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM