Use jquery to re-populate form with JSON data

前端 未结 3 704
独厮守ぢ
独厮守ぢ 2020-12-13 10:27

I have an HTML form, that I save to the database via ajax. To get the query string of key/value pairs, I have used the very convenient serialize function, like

相关标签:
3条回答
  • 2020-12-13 10:33

    I'd say the easiest way would be something along these lines:

    // reset form values from json object
    $.each(data, function(name, val){
        var $el = $('[name="'+name+'"]'),
            type = $el.attr('type');
    
        switch(type){
            case 'checkbox':
                $el.attr('checked', 'checked');
                break;
            case 'radio':
                $el.filter('[value="'+val+'"]').attr('checked', 'checked');
                break;
            default:
                $el.val(val);
        }
    });
    

    Basically, the only ones that are odd are the checkboxes and radios because they need to have their checked property, well, checked. The radios are a little more complex than the checkboxes because not only do we need to check them, we need to find the right ONE to check (using the value). Everything else (inputs, textareas, selectboxes, etc.) should just have its value set to the one that's returned in the JSON object.

    jsfiddle: http://jsfiddle.net/2xdkt/

    0 讨论(0)
  • 2020-12-13 10:34

    I suggest you change the way you are making an ajax request. Use .post()

    $.post("my_save_script.php", {
             data: myData,
        }, function(data) {
            $.each(data, function(i, item){
                $("#"+item.field).val(item.value);
            });      
        }, 
    "json");
    
    0 讨论(0)
  • 2020-12-13 10:48

    If data[0] contains the name of the field and data[1] contains the value then you can do the following:

    You can do something like this for text boxes:

    $("[name="+data[0]+"]").val(data[1]);
    

    Then something like this for selects:

    $("[name="+data[0]+"]").val(data[1]);
    

    Please note that check boxes and radio buttons are only serialized if they are checked.

    So something like this for check boxes (before jQuery 1.6+):

    $("[name="+data[0]+"]").attr('checked','checked');
    

    The radio button might need some additional work depending on how you're differentiating between the different ones. (I.E. Id, value, etc..)

    0 讨论(0)
提交回复
热议问题