Using jQuery and JSON to populate forms?

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

    With little improvements (except radio buttons):

    function resetForm($form)
    {
        $form.find('input:text, input:password, input:file, select, textarea').val('');
        $form.find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
    }
    
    function populateForm($form, data)
    {
        resetForm($form);
        $.each(data, function(key, value) {
            var $ctrl = $form.find('[name='+key+']');
            if ($ctrl.is('select')){
                $('option', $ctrl).each(function() {
                    if (this.value == value)
                        this.selected = true;
                });
            } else if ($ctrl.is('textarea')) {
                $ctrl.val(value);
            } else {
                switch($ctrl.attr("type")) {
                    case "text":
                    case "hidden":
                        $ctrl.val(value);   
                        break;
                    case "checkbox":
                        if (value == '1')
                            $ctrl.prop('checked', true);
                        else
                            $ctrl.prop('checked', false);
                        break;
                } 
            }
        });
    };
    

提交回复
热议问题