开发者

How can I make an option selected in <select></select> tag with jQuery?

How can i make this script make certain items selected. also in $("myselect[value='"value"']").attr('selected', 'selected'); "value" is supposed to be variable. so far this does not work for me even if i put US instead of "variable" when it prints it with first command it never makes it selected.

$.ajax({
    url:'suggest.html',
    type:'POST',
    data: 'q=' + str,
    dataType: 'json',
    success: function开发者_如何学C( json ) {
        $.each(json, function(i, value) {
        if (value=='US>') {
            $('#myselect').append($('<option>').text(value).attr('value', value));
        $("myselect[value='"value"']").attr('selected', 'selected');
        } else {
        $('#myselect').append($('<option>').text(value).attr('value', value));
        };             

        });
    }
});


This should work:

$('#myselect').val(value);


It is your jquery selector that you are using to get the option you just appended that isnt working. You can chain your attribute methods together though so you dont actually need the second selector anyway...

$.ajax({
    url:'suggest.html',
    type:'POST',
    data: 'q=' + str,
    dataType: 'json',
    success: function( json ) {
        $.each(json, function(i, value) {
        if (value=='US>') {
            $('#myselect').append($('<option>').text(value).attr('value', value).attr('selected', 'selected'));
        } else {
        $('#myselect').append($('<option>').text(value).attr('value', value));
        };             

        });
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜