Crainer
Crainer

Reputation: 11

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

        });
    }
});

Upvotes: 1

Views: 2696

Answers (2)

grc
grc

Reputation: 23545

This should work:

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

Upvotes: 3

Dean North
Dean North

Reputation: 3780

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

        });
    }
});

Upvotes: 0

Related Questions