0

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

我正在使用的 jQuery 函数(from )是

(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

我希望这是由于[]名称中的,但无法弄清楚该怎么做。

4

2 回答 2

1

您必须将您的名字中的and 替换为 and [(如此所述),因为(如您所知)它们在 jQuery 选择器中具有特殊含义。]\\[\\]

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

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

要确定复选框和单选按钮,您需要设置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());
            }
        })
    })
}
于 2012-09-05T19:06:33.097 回答
0

尝试使用data属性。

data-name="cartype[]"

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

于 2012-09-05T19:04:21.617 回答