jQuery克隆元素,然后用连接的结果填充隐藏字段,以避免空列表问题

jQuery Cloning Elements then populating hidden field with concatenated results to avoid empty list issue

本文关键字:字段 隐藏 列表 填充 问题 结果 元素 然后 连接 jQuery      更新时间:2023-09-26

我从朋友的博客中得到一些代码,使用jQuery复制表单元素,效果很好:

$('#btnAdd').click(function() {
    var num     = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
    var newNum  = new Number(num + 1);      // the numeric ID of the new input field being added
    // create the new element via clone(), and manipulate it's ID using newNum value
    var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
    // manipulate the name/id values of the input inside the new element
    newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum);
    // insert the new element after the last "duplicatable" input field
    $('#input' + num).after(newElem);
    // enable the "remove" button
    $('#btnDel').attr('disabled','');
    // business rule: you can only add 5 names
    if (newNum == 5)
        $('#btnAdd').attr('disabled','disabled');
});
$('#btnDel').click(function() {
    var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
    $('#input' + num).remove();     // remove the last element
    // enable the "add" button
    $('#btnAdd').attr('disabled','');
    // if only one element remains, disable the "remove" button
    if (num-1 == 1)
        $('#btnDel').attr('disabled','disabled');
});

这适用于包含"address1,address2,city,state,zip"字段的地址块。这样,当提交表单时,我只需遍历列表以将值插入到表中。但是因为address2中并不总是有一个条目,所以我得到的列表并不能告诉我它实际上属于哪个列表元素。

所以,另一个朋友建议,在表单提交时,我从表单字段中获取值,将分隔符更改为|(一个好主意)并将它们填充到隐藏字段中(我称之为hidden_address1, hidden_address2, hidden_city等)。然后他给了我这个代码,这个代码不工作:

var values = [];
$('.address1').each(function() {
    values.push($(this).val());
});
$('#hidden_field').val(values.join('|'));

所以我在五个字段上复制了这个,增加了值。长度= 0;

这是我不太擅长的jQuery领域。我做错了什么?:)

首先,我建议每次将values变量设置为一个新的空数组,而不是将长度设置为0:

values = [] //instead of values.length = 0

但是它不起作用的真正原因是因为你选择了像这样的隐藏表单:

$('#hidden_address1').val(values.join('|'));

但是HTML中的表单是这样的:

<input type="hidden" value="" name="hidden_address1">

所以你试图选择一个ID为hidden_address1的元素,但没有这样的元素存在,你隐藏的表单没有ID。您需要将标记更改为:

<input type="hidden" value="" name="hidden_address1" id="hidden_address1">

这应该能解决你的问题