Last time I asked about the reverse process, and got some very efficient answers. I'm aiming for least lines of code here. I have a form of fields and an associative array in the {fieldname:data} format, I want to populate a corresponding form with it.
If your form elements have their ID set to the fieldname:
$.each(myAssocArry, function(i,val) { $('#'+i).val(val); });
When I did this for a project, I found that setting the value of select fields, radio buttons and checkboxes necessitated more complex code, something along the lines of:
jQuery.each(data, function (name,value) {
jQuery("input[name='"+name+"'],select[name='"+name+"']").each(function() {
switch (this.nodeName.toLowerCase()) {
case "input":
switch (this.type) {
case "radio":
case "checkbox":
if (this.value==value) { jQuery(this).click(); }
break;
default:
jQuery(this).val(value);
break;
}
break;
case "select":
jQuery("option",this).each(function(){
if (this.value==value) { this.selected=true; }
});
break;
}
});
});
I haven't tested this code so I hope there are no silly syntax errors that I should have caught. Hope this helps.
I am not allowed to comment on the comments here (yet), so .... As noted in the comment, the jQuery .val(val) method handles setting radio buttons,checkboxes and selects.
You will still need to put select[name=...] into your jQuery selector pattern or the select elements won't be updated.
Or similar to the previous suggestion using the field names instead of ids:
$.each(data, function(name,value) {
$("input[name='" + name + "']").val(value);
});
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