JQuery setting select as selected - not not updating

forms, jquery

Solution

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.

Problem

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?

Original source