Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate a form with data from an associative array with jQuery

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.

like image 389
Vasil Avatar asked Oct 05 '08 19:10

Vasil


3 Answers

If your form elements have their ID set to the fieldname:

$.each(myAssocArry, function(i,val) { $('#'+i).val(val); });
like image 177
Adam Bellaire Avatar answered Oct 17 '22 17:10

Adam Bellaire


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.

like image 21
J5. Avatar answered Oct 17 '22 18:10

J5.


Or similar to the previous suggestion using the field names instead of ids:

$.each(data, function(name,value) {
    $("input[name='" + name + "']").val(value);
});
like image 5
Eran Galperin Avatar answered Oct 17 '22 18:10

Eran Galperin