jQuery填充表单与数据表单数组问题

时间:2011-05-26 23:09:32

标签: jquery forms

我有以下功能,我试图填写具有指定ID的表单。

function input_form(form, data_array)
{
$.each(data_array, function(key, value){
    //alert(key + " = " + value);
    $(form).find('input[name="'+key+'"]').each(function()
    {
        switch(this.type)
        {
            case 'select-one':
            case 'select-multiple':
                $('input[name="'+key+'"] value:contains("'+value+'")').attr('selected','selected');
                break;
            case 'password':
            case 'text':
            case 'textarea':
                //alert(key + " = " + value);
                $('input[name="'+key+'"]').val(value);
                break;
            case 'checkbox':
            case 'radio':
                $('input[name="'+key+'"] value:name("'+value+'")').attr('checked','checked');
            //this.checked = true;
        }
    });
});
}

我有以下问题:

  1. 它填写文本框很好,但不适用于收音机和复选框。

  2. 我有另一个具有相同名称值的表单,即使表单具有不同的ID,它也会填写该表单。

  3. var form ='#form1'

    var data_array =键是要由值填充的表单的名称值。

    任何人都可以看到我出错的地方或者是否有任何其他问题。

    感谢。

    感谢Matt BAll提供更清晰的代码。我编辑了收音机和复选框,因为它选择了最后一个收音机而不是实际选择的收音机。

    function input_form(form, data_array)
    {
        $.each(data_array, function(key, value){
            //alert(key + " = " + value);
            $(form).find('input[name="'+key+'"]').each(function()
            {
                var $this = $(this);
                switch(this.type)
                {
                    case 'select-one':
                    case 'select-multiple':
                        $this.attr('selected', true);
                        break;
                    case 'password':
                    case 'text':
                    case 'textarea':
                        $this.val(value);
                        break;
                    case 'checkbox':
                    case 'radio':
                        //
                        if($(this).val() == value)
                        {
                            this.checked = true;
                        }
                }
            });
        });
    }
    

1 个答案:

答案 0 :(得分:1)

尝试使用此尺寸。

function input_form(form, data_array)
{
    $.each(data_array, function(key, value){
        //alert(key + " = " + value);
        $(form).find('input[name="'+key+'"]').each(function()
        {
            var $this = $(this);
            switch(this.type)
            {
                case 'select-one':
                case 'select-multiple':
                    $this.attr('selected', true);
                    break;
                case 'password':
                case 'text':
                case 'textarea':
                    $this.val(value);
                    break;
                case 'checkbox':
                case 'radio':
                    this.checked = true;
            }
        });
    });
}
相关问题