简体   繁体   English

使用JQUERY以动态创建的形式命名两个不同的输入

[英]Naming two different inputs in a dynamically created form with JQUERY

I am writing a program which requires a text box and a textarea to be added dynamically to a form. 我正在编写一个程序,该程序需要将文本框和文本区域动态添加到表单中。 I am using the clone function for this purpose. 我正在为此目的使用克隆功能。 Unfortunately, I cannot seem to figure out how to make each box have a unique ID. 不幸的是,我似乎无法弄清楚如何使每个盒子都有唯一的ID。 Here is my Jquery: 这是我的Jquery:

<script type="text/javascript"> 
$(document).ready(function() {

$('#addButton').click(function() {
var num = $('.clonedInput').length;
var newNum = new Number(num + 1);

var newElem = $('#form1').clone().attr('id', 'form' + newNum);
newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name');

$('#form' + num).after(newElem);

$(newElem).append(
   $(document.createElement('input')).attr({
       id:    'myCheckbox'  + newNum
      ,name:  'myCheckbox' + newNum
      ,value: 'myValue'
      ,type:  'checkbox'
   })
);
});

})
</script>

And my HTML: 而我的HTML:

 <form method="post" form action="save3.php">
 <div name="forms" id="form1" class="clonedInput" width="800px">
     <label></label><textarea rows="4" cols="50" id="text1" class="text" name="text[]"      ></textarea>
 <label></label><input type="text" id="title1" class="title" name="title[]">
 </div>
 </form>

Thank you in advance for your help 预先感谢您的帮助

your code is wrong: http://jsfiddle.net/mig1098/bk40jd9f/ 您的代码是错误的: http : //jsfiddle.net/mig1098/bk40jd9f/

$(document).ready(function() {

$('#addButton').click(function() {

var num = $('.clonedInput').length;
var newNum = new Number(num + 1);

var newElem = $('#form1').clone().attr('id', 'form' + newNum);
newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name');

$('#form' + num).after(newElem);

$(newElem).append(
   $(document.createElement('input')).attr({
       id:    'myCheckbox'  + newNum
      ,name:  'myCheckbox' + newNum
      ,value: 'myValue'
      ,type:  'checkbox'
      })
   );
 });

})

Your problem seems to be that you're only renaming the attribute values for the first child, the label that correctly gets the id attribute value "name2": 您的问题似乎是您只在重命名第一个孩子的属性值,即正确获取id属性值“ name2”的标签:

newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name');

But I can't see any code that takes care of the textarea and the input field in the same manner. 但是我看不到任何以相同方式处理文本区域和输入字段的代码。 There are several ways you could do this, one being this: 您可以通过多种方式执行此操作,其中一种是:

$('#form' + newNum + ' textarea').attr('id','text' + newNum);
$('#form' + newNum + ' input[type="text"]').attr('id','title' + newNum);

See http://jsfiddle.net/bk40jd9f/1/ 参见http://jsfiddle.net/bk40jd9f/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM