Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery setting select as selected - not not updating

Tags:

jquery

forms

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?

like image 832
TH1981 Avatar asked Mar 12 '13 17:03

TH1981


4 Answers

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.

like image 59
BBagi Avatar answered Nov 11 '22 00:11

BBagi


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

For select2, use:

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

For selectmenu, use:

$('#myselect').selectmenu('refresh', true);
like image 39
Marquinho Peli Avatar answered Nov 11 '22 00:11

Marquinho Peli


Replace

.attr('selected', true);

for

.prop('selected', true);

that is new in jquery 1.6.x+

like image 26
Nelson Avatar answered Nov 11 '22 00:11

Nelson


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

$('form input[name="'+k+'"]:selected').length == 1
like image 21
Monica Lent Avatar answered Nov 11 '22 00:11

Monica Lent