【问题标题】:cloning form fields are populated with value from previous fields克隆表单字段由先前字段的值填充
【发布时间】:2012-06-01 17:38:51
【问题描述】:

当用户单击添加按钮时,此函数会在 div 中克隆一组文本输入字段:

function addRows(label, maxRows, minRows) {
  $('.add-' + label).live('click', function() {
    if ($("." + label + "-group").length < maxRows) {
      $('#' + label + '-template')
        .clone()
        .removeAttr('id')
        .insertAfter($(this).closest('.' + label + '-group'))
        .find('.minus')
        .show();
    }
  });
}

当用户填写一个字段,然后单击添加按钮时,它会显示一个新的字段行,但它们会填充用户在前一行中输入的值。

解决此问题的最佳方法是什么?我想我可以清空该行实例的所有输入文本字段。

我只是不知道如何清除相应的行。

字段名称为:first_name[], last_name[], phone[]

因此,当它将这三个字段克隆到新行时,它们将与上面的字段具有相同的名称。

当用户提交时,我会遍历first_name[], last_name[], phone[]中的每个值

【问题讨论】:

  • 首先,live 在新版本的 jQuery 中被弃用。最好使用on 或事件委托。
  • 注入后在输入上设置 .val('')
  • The .clone() method performs a deep copy of the set of matched elements, meaning that it copies the matched elements as well as all of their descendant elements and text nodes. 直接来自 jQuery API。按照下面的回答清除.val() 可能会起作用。
  • @SethenMaleno live 在支持on 的jquery 版本中调用on,实际上没有任何理由让人们将live 更改为on
  • @SethenMaleno - 我应该用什么代替 clone()?

标签: javascript jquery html forms


【解决方案1】:

试试这个,在appendToinsertAfter等其他方法之后调用val()

$('#' + label + '-template').clone().val("")...

http://jsfiddle.net/pnQhh/

【讨论】:

  • $('#' + label + '-template').find('input').val('');
  • @Brad 这使得原始输入值为无,您可以在克隆后调用val()
猜你喜欢
  • 2013-02-10
  • 1970-01-01
  • 1970-01-01
  • 2020-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多