Javascript,克隆后修改元素

时间:2014-12-05 11:03:30

标签: javascript jquery html

我试图发布一个表单的克隆部分但由于元素名称相同而没有全部提交。

有没有人知道克隆过程中更改输入名称属性的最佳过程?

<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>

1 个答案:

答案 0 :(得分: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。 我仍然更喜欢名称/数组解决方案,它更容易处理服务器端,因为你可以遍历字段而不是要求未知数量的新字段。