简体   繁体   中英

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?

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.

Replace

.attr('selected', true);

for

.prop('selected', true);

that is new in jquery 1.6.x+

为了完整起见,你也可以这样检查:

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

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

For select2, use:

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

For selectmenu, use:

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

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