TH1981
TH1981

Reputation: 3193

JQuery setting select as selected - not not updating

I've done this a hundred times before, but in this one instance I can't get it to work.

I have a form. you choose from a dropdown of clients and it updates the remaining fields in the form.

simples.

I use an ajax call and return the form data as a json object and then use the following jquery to update the on-screen form. The fields are setup so that the name matches the output definition (in below as k).

    $.each(out, function(k,v){
        if($('form input[name="'+k+'"]').attr('type') == 'text'){
            $('form input[name="'+k+'"]').val(v);
        }else if($('form input[name="'+k+'"]').attr('type') == 'hidden'){
            $('form input[name="'+k+'"]').val(v);
            $('form .'+k).text(v);
        }else if($('form input[name="'+k+'"]').attr('type') == 'checkbox'){
            if(v == '1') {
                $('form input[name="'+k+'"]').attr('checked', true);
            }else{
                $('form input[name="'+k+'"]').attr('checked', false);
            }
        }else
        $('form select[name="'+k+'"] option[value="'+v+'"]').attr('selected', true);

        $('form input[name="old_client_name"]').val(out.client_name);
    });

When I use the inspect element, I can actually see in the one select field that the correct option has been given the selected="selected" value but the user's view isn't updating the select box to reflect this, so the user can't see this as selected, and in processing the form, it acts like the value hasn't been set.

I'm using jq 1.9.1, but have only recently upgraded to this on this particular project.

Any suggestions?

Upvotes: 7

Views: 11317

Answers (4)

Marquinho Peli
Marquinho Peli

Reputation: 5129

If you are using some plugin, see specific documentation. Examples:

For select2, use:

$('#myselect').trigger('change');

For selectmenu, use:

$('#myselect').selectmenu('refresh', true);

Upvotes: 5

Monica Lent
Monica Lent

Reputation: 261

Just for completeness' sake, you can also check it this way:

$('form input[name="'+k+'"]:selected').length == 1

Upvotes: 1

Replace

.attr('selected', true);

for

.prop('selected', true);

that is new in jquery 1.6.x+

Upvotes: 2

BBagi
BBagi

Reputation: 2085

try:

    $('form select[name="'+k+'"] option[value="'+v+'"]').attr('selected', 'selected');

or:

    $('form select[name="'+k+'"] option[value="'+v+'"]').prop('selected', 'selected');

For clarity, you should always set selected="selected", not just true.

Upvotes: 7

Related Questions