jQuery-将表单复制到相同的表单

jQuery - Copying form to identical form

本文关键字:表单 复制 jQuery-      更新时间:2023-09-26

我想将一个现有表单复制到另一个表单。我发现这个问题适用于正常输入,但它在我的复选框上抛出了一个错误

我使用的jQuery函数是

(function($) {
    $.fn.copyNamedTo = function(other) {
        return this.each(function() {
            $(':input[name]', this).each(function() {
                $('[name=' + $(this).attr('name') +']', other).val($(this).val())
            })
        })
    }
}(jQuery));

错误为:

Uncaught Error: Syntax error, unrecognized expression: [name=cartype[]] 

复选框的排列方式如下:

<input type="checkbox" name="cartype[]" id="cartype_10" value="10">4x4
<input type="checkbox" name="cartype[]" id="cartype_11" value="11">Saloon

我想这是由于名称中的[],但不知道该怎么办。

您必须将名称中的[]替换为''[''](如下所示),因为(正如您所知)它们在jQuery选择器中具有特殊含义。

$('[name=' + $(this).attr('name').replace(/(['[']])/g, '''''$1') +']', other).val($(this).val())

请注意,从技术上讲,您还应该有一个形式为$('[name="val"]')的选择器(注意属性值周围的引号)。jQuery对此似乎一直很宽容,但它符合文档。

要确定复选框和单选按钮,需要设置它们的checked属性,而不是更改值。您可以将您的功能更改为此;

$.fn.copyNamedTo = function(other) {
    return this.each(function() {
        $(':input[name]', this).each(function() {
            var target = $('[name=' + $(this).attr('name').replace(/(['[']])/g, '''''$1') +']', other);
            // Radios have the same name as each other, so filter based on value
            // Checkboxes are in the same boat here due to the naming conventions shown in the OP.
            if ($(this).is(':checkbox, :radio')) {
                target.filter('[value="' + this.value + '"]').prop('checked', this.checked);
            } else {
                target.val($(this).val());
            }
        })
    })
}

尝试使用data属性。

data-name="cartype[]"

并使用:$(this).data('name')

抓取