Using jQuery and JSON to populate forms?

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

    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));
    }
    

提交回复
热议问题