2013-03-03 99 views
0

我有一个html表单。一个条目可以多次添加不同的值,并以数组的名字命名(如fieldname[])。点击[+]按钮使用[ - ]按钮创建新的字段,单击时将删除该条目。jQuery动态表单字段数组

<table cellpadding="0" cellspacing="0"> 
<tr> 
<td>Item</td> 
<td id="resource"> 
<input id="item" name="item[]" type="text" value=""> 
</td> 
<td> 
<img id="addScnt" alt="[+]">&nbsp;</td> 
</tr> 
<br> 
<button id="go">go</button> 
</table> 

jQuery(document).ready(function($){ 
    var scntDiv = $('#resource'); 
    var i = $('#resource p').size() + 1; 
    var name = $('#resource p'); 
    $('#addScnt').live('click', function() { 
     $('<tr><td class="" id=""><input id="item" name="item[]" type="text" value=""><img id="remScnt" alt="[-]"></td></tr>').appendTo(scntDiv); 
     i++; 
     return false; 
    }); 
    $('#remScnt').live('click', function() { 
     if(i > 1) { 
       $(this).parent().parent().remove(); 
       i--; 
     } 
     return false; 
    }); 
}); 

这里是fiddle

我想要什么,当我点击进入按钮,数组应与输入元素创建,开始与第1项的值索引0。此外,行应给予ID使用相同的值(0为第一行,1为第二等..)。我已经在CSS上定义了一些ID,如果分配了ID,它可能会改变颜色。数组可能会最终警告(我想用ajax来传递值)。

我该怎么做?

回答

1

你应该table添加行不td所以首先要编写它proper format

它应该是这样的:

<table cellspacing="0" cellpadding="0" id="table"> 
<tbody> 
    <tr> 
     <td>Item</td> 
     <td id="resource"> 
      <input type="text" value="" name="item[]" id="item" class=""> 
     </td> 
     <td> 
      <img alt="[+]" id="addScnt" class="add">&nbsp;</td> 
    </tr> 
    <tr> 
     <td>Item</td> 
     <td id="" class=""><input type="text" value="" name="item[]" id="item"></td> 
     <td><img alt="[-]" id="remScnt" class="minus"></td> 
    </tr> 
</tbody> 
</table> 

并用于按钮go

代码是小提琴

$('#go').live('click',function(){ 
    $('input[name="item[]"]').each(function(){ 
    alert($(this).val());//code what you want on click of button 
    }); 
}); 

检查http://jsfiddle.net/hjNdb/5/

1

下面是一个例子:http://jsfiddle.net/hjNdb/2/

$(function() { 
    var scntDiv = $('#resource'); 
    var i = $('#resource p').size() + 1; 
    var name = $('#resource p'); 
    $('#addScnt').live('click', function() { 
     var id = $('input').length; // Id attribution 
     $('<tr><td class=""><input id="item' + id + '" name="item[]" type="text" value=""><img id="remScnt" alt="[-]"></td></tr>').appendTo(scntDiv); 
     i++; 
     return false; 
    }); 
    $('#remScnt').live('click', function() { 
     if (i > 1) { 
      $(this).parent().parent().remove(); 
      i--; 
     } 
     return false; 
    }); 

    //Array construction 
    $('#go').click(function() { 
     var myArray = []; 
     $('input').each(function() { 
      myArray.push($(this).val()); 
     }); 
     alert(myArray) 
    }); 
}); 
+0

是有什么办法可以输出指数也?并将该号码分配为行ID? – 2013-03-03 12:53:46