Using jQuery and JSON to populate forms?

前端 未结 10 1082
忘掉有多难
忘掉有多难 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

    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 
    

提交回复
热议问题