2014-12-05 98 views
0

我試圖發佈表單的克隆部分,但由於元素名稱相同,它不提交全部。Javascript,修改克隆後的元素

有誰知道在克隆過程中更改輸入名稱屬性的最佳過程嗎?

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
<script> 
$(document).ready(function(){ 
    $("button").click(function(){ 
    if (checkMACAddress()==true) { 
    $("#test").clone().insertAfter("div.test-row:last"); 
    } 
    }); 
}); 
    function checkMACAddress() { 
       var valid = true; 
       for (var i = 0, l = document.getElementsByName("mac").length; i < l; i++) { 
     var macAddress=document.getElementsByName("mac")[i].value; 
     var macAddressRegExp=/^(?:[0-9A-F]{2}[:]?){5}(?:[0-9A-F]{2}?)$/i; 

     if (macAddressRegExp.test(macAddress)==false) { //if match failed 
      alert("MAC Invalid - Must be IEEE.802 example 00:3F:00:10:00:2C"); 
      valid=false; 
     } 
       } 
     return valid; 
    } 
</script> 
<h3>Account Details</h3> 
<div class="row"> 
    <div class="columns small-4"> 
       <label>Destination Account Number*</label> 
     [[input||type=text||name=Account||name_literal=Account||placeholder=12345||required=required]] 
    </div> 
</div> 
<hr> 
<h3>Device Details</h3> 
<h5> 
     <button type='button'>Add Device</button> 
</h5> 
<div id="test" class="test-row"> 
    <div class="columns small-3"> 
     <label>MAC - IEEE.802 Format Only</label> 
     [[input||type=text||name=mac||name_literal=mac||placeholder=54781A139264||required=required]] 
    </div> 
    <div class="columns small-3"> 
     <label>Extension/Seat Number</label> 
     [[input||type=text||name=seat||name_literal=seat||placeholder=200]] 
    </div> 
    <div class="columns small-3"> 
     <label>Display Name</label> 
     [[input||type=text||name=station||name_literal=station||placeholder=reception desk]] 
    </div> 
+0

這是克隆的元素? – 2014-12-05 11:04:14

+0

其整個div「測試」 – 2014-12-05 11:17:18

回答

0

一種方法是使用數組語法作爲字段名稱,例如:data[identifier][]。否則,你就需要克隆後修改的name屬性:

var c = 0; 
// each time you click on the button... 
$(".clone").on('click',function(){ 
    // generate a new clone of complete test div.. 
    var klon = $('#test').clone(); 
    // append it to parent element (or after existing, as you like) 
    $('#test').parent().append(klon); 
    // increase global counter... 
    c++; 
    // inside clone find all inputs 
    // (if you other form elements, you must add them in selector) 
    klon.find('input').each(function() { 
     var $this = $(this), 
      name = $this.attr('name'); 
     // update name attribute 
     $this.attr('name', name + '_' + (c)); 

    }); 
}); 

看到一個fiddle這裏。 我仍然更喜歡名稱/數組解決方案,它更容易處理服務器端,因爲您可以遍歷字段而不是詢問未知數量的新字段。

+0

這附加克隆的div名稱。如何輕鬆地在div內附加子元素。孩子輸入名稱等.. – 2014-12-08 11:34:04

+0

@RossBeer我已經更新了答案,並添加了一個小提琴來演示名稱屬性的動態變化。正如我在答案中評論的,我更喜歡你的例子中的名稱/數組變體,例如mac [],seats []。 – 2014-12-08 12:16:28