2012-04-05 132 views
0

我想动态添加输入字段,我能够做到这一点。但我不知道如何去添加一个新的名字到输入字段。我希望它是一个递增的数字。因此,第一组输入字段将是input1,并且每个创建的克隆都会增加数字:input1,input2,input3等等。有没有人知道我该如何去做这件事?这里是的jsfiddle:http://jsfiddle.net/liveandream/Xs7m8/在jQuery中创建输入字段的克隆和更新字段ID

这里是我的代码:

HTML:

<form action="#" method="post"> 
<div class="avail"> 
     <div class="roomType"> 
      <p>Tipo de Habitación:<br /> 
     <input type="text" name="roomType" /></p></div> 
     <div class="roomType"> 
      <p><span class="small">Fecha de inicio:</span><br /> 
     <input type="text" name="Date1" /></p></div> 
     <div class="roomType"><p><span class="small">Fecha de Termino:</span><br /> 
     <input type="text" name="Date2" /></p></div> 
     <div class="roomType"> 
      <p>Tarifa:<br /> 
     <input type="text" name="roomRate" /></p></div><br clear="all" /> 
</div> 
<input type="submit" value="+" id="copy" /> 
<input type="submit" value="Add to Database" name="add" /> 

而且我的Jquery:

$("#copy").click(function(e) { 
     $(".avail").clone().removeAttr('id').insertBefore(this); 
     e.preventDefault(); 
    }); 

预先感谢您的任何人都愿意帮助! !

+0

你可以不使用它作为数组'name =“Date1 []”','name =“Date2 []”' - 在这种情况下,你有每个表单的数据发布数组? – Elen 2012-04-05 15:09:09

回答

0

(删除我的初步答案 - 忽略在HTML现有的IDS)

你可以组后的结果通过房间。

results = {}; 
$('form').submit(function(e) { 
    e.preventDefault(); // prevent automatic submitting 

    $('.avail').each(function(index) { 
     // Here your have the gather the fields and values in result array; 

     results['room'+index] = result; // add array with results of one room to result 
    }); 

    // Post the result 
    $.post($(this).attr('action'), results, function(result) { 
     // callback 
    }); 
}); 
+0

这是一个不错的尝试,但它没有工作:(我打算玩一下,看看它是否有效。非常感谢你花时间做到这一点! – liveandream 2012-04-05 16:00:42

+0

好吧,请更新如果你遇到一些具体问题请注意,我没有测试过我的代码,但这应该会给你明确的指示,我希望。 – 2012-04-05 16:06:00