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.
If you are using some plugin, see specific documentation. Examples:
For select2, use:
$('#myselect').trigger('change');
For selectmenu, use:
$('#myselect').selectmenu('refresh', true);
Replace
.attr('selected', true);
for
.prop('selected', true);
that is new in jquery 1.6.x+
Just for completeness' sake, you can also check it this way:
$('form input[name="'+k+'"]:selected').length == 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With