Using jQuery and JSON to populate forms?

前端 未结 10 1011
忘掉有多难
忘掉有多难 2020-12-04 10:41

I was wondering how is it popssible to populate forms using JSON?

I have a JSON string which I get using php\'s json_encode() And I want to use the JSON

相关标签:
10条回答
  • 2020-12-04 11:11

    There is a problem here with textarea, then I change it to a default switch value

    Use this to assign values to Many Controls :

    function populate(frm, data) {   
        $.each(data, function(key, value) {  
            var ctrl = $('[name='+key+']', frm);  
            switch(ctrl.prop("type")) { 
                case "radio": case "checkbox":   
                    ctrl.each(function() {
                        if($(this).attr('value') == value) $(this).attr("checked",value);
                    });   
                    break;  
                default:
                    ctrl.val(value); 
            }  
        });  
    }
    
    0 讨论(0)
  • 2020-12-04 11:11

    Thanks Nowshath. It worked for me. I added a extra check in your version to be able to populate select options as well.

    function populateForm(frm, data) {   
    $.each(data, function(key, value){  
        var $ctrl = $('[name='+key+']', frm); 
        if($ctrl.is('select')){
            $("option",$ctrl).each(function(){
                if (this.value==value) { this.selected=true; }
            });
        }
        else {
            switch($ctrl.attr("type"))  
            {  
                case "text" :   case "hidden":  case "textarea":  
                    $ctrl.val(value);   
                    break;   
                case "radio" : case "checkbox":   
                    $ctrl.each(function(){
                       if($(this).attr('value') == value) {  $(this).attr("checked",value); } });   
                    break;
            } 
        } 
    });  
    
    
    }; // end of populateForm() function 
    
    0 讨论(0)
  • 2020-12-04 11:11

    This is an apendix to @Nowshath's answer

    This works for multilevel objects as well

     populateForm(form, data) {
        $.each(data, function(key, value) {
    
            if(value !== null && typeof value === 'object' ) {
                this.populateForm(form, value);
            }
            else {
                var ctrl = $('[name='+key+']', form);
                switch(ctrl.prop("type")) {
                    case "radio": case "checkbox":
                    ctrl.each(function() {
                        $(this).prop("checked",value);
                    });
                    break;
                    default:
                        ctrl.val(value);
                }
            }
        }.bind(this));
    }
    
    0 讨论(0)
  • 2020-12-04 11:13

    In case anyone is looking to populate from a multidimensional json format, such as the result of $.serializeJSON[ https://github.com/marioizquierdo/jquery.serializeJSON ], here's a function to convert to a flat format.

    function json2html_name_list(json, result, parent){
        if(!result)result = {};
        if(!parent)parent = '';
        if((typeof json)!='object'){
            result[parent] = json;
        } else {
            for(var key in json){
                var value = json[key];
                if(parent=='')var subparent = key;
                else var subparent = parent+'['+key+']';
                result = json2html_name_list(value, result, subparent);
            }
        }
        return result;
    }
    

    Usecase example with the functions above:

    populateForm($form, json2html_name_list(json))
    

    With all the examples above though:

    var $ctrl = $('[name='+key+']', frm);
    

    needs to be changed to

    var $ctrl = $('[name="'+key+'"]', frm);
    

    to prevent a syntax error with jQuery

    Take note list arrays have to be written with numbers(e.g. fruit[0], instead of fruit[]) in order to be work with this function.

    0 讨论(0)
  • 2020-12-04 11:15

    For just text controls (i.e. no radios or checkboxes), you can make a simple version of a populate function:

    function populate(frm, data) {
      $.each(data, function(key, value){
        $('[name='+key+']', frm).val(value);
      });
    }
    

    Usage example:

    populate('#MyForm', $.parseJSON(data));
    

    Demo: http://jsfiddle.net/Guffa/65QB3/3/

    0 讨论(0)
  • 2020-12-04 11:24

    For a weird but valid JSON syntax like

        [{'name':<field_name>,'value':<field_value>},
        {'name':<field_name>,'value':<field_value>},
        {'name':<field_name>,'value':<field_value>},
        {'name':<field_name>,'value':<field_value>}]
    

    look at this http://jsfiddle.net/saurshaz/z66XF/

    We had this weird syntax being used in our application and we got around by writing the logic as above.

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