使用jquery循环遍历表

时间:2014-02-05 09:09:13

标签: jquery

如何在表格中循环并在javascript中创建对象

var employees = [];
 if(first td element is hidden)
{
  employes[rowindex].Id=element.val();
}
else
{
 employees[rowindex].Name=element.val();
}
employees[rowindex].countryId= selected value from dropdown

 <table id="employeeTable" class="table table-bordered table-striped">
 <tr><td>Name</td> <td>Age</td><td>Country</td><td>Delete</td></tr>
 <tr>
 <td>
 <input data-val="true" data-val-number="The field Id must be a number." data-val-required="The Id field is required." id="Employees_0__Id" name="Employees[0].Id" type="hidden" value="1" />
 <input class="form-control" id="Employees_0__Name" name="Employees[0].Name" type="text" value="arjun" />
 <span class="field-validation-valid" data-valmsg-for="Employees[0].Name" data-valmsg-replace="true"></span>
 </td>
 <td><input class="form-control" data-val="true" data-val-number="The field Age must be a number." data-val-required="The Age field is required." id="Employees_0__Age" name="Employees[0].Age" type="text" value="25" /></td>

 <td>

 <select data-val="true" data-val-number="The field CountryId must be a number." data-val-required="The CountryId field is required." id="Employees_0__CountryId" name="Employees[0].CountryId"><option selected="selected" value="1">USA</option>
<option value="2">UK</option>
</select>
 </td>
 <td>
 <a class="glyphicon glyphicon-remove"
 href="#"></a>
 </td>
 </tr>

 <td>
 <input data-val="true" data-val-number="The field Id must be a number." data-val-required="The Id field is required." id="Employees_1__Id" name="Employees[1].Id" type="hidden" value="2" />
 <input class="form-control" id="Employees_1__Name" name="Employees[1].Name" type="text" value="Kumar" />
 <span class="field-validation-valid" data-valmsg-for="Employees[1].Name" data-valmsg-replace="true"></span>
 </td>
 <td><input class="form-control" data-val="true" data-val-number="The field Age must be a number." data-val-required="The Age field is required." id="Employees_1__Age" name="Employees[1].Age" type="text" value="34" /></td>

 <td>

 <select data-val="true" data-val-number="The field CountryId must be a number." data-val-required="The CountryId field is required." id="Employees_1__CountryId" name="Employees[1].CountryId"><option value="1">USA</option>
<option selected="selected" value="2">UK</option>
</select>
 </td>


 <td>
 <a class="glyphicon glyphicon-remove"
 href="#"></a>
 </td>

 </tr>
 </table>

1 个答案:

答案 0 :(得分:1)

var obj = [];

$('input[type=text], input[type=hidden], select').each(function(i,itm){
    var inpName = $(itm).attr('name'),
        name = inpName.match(/(\w+)$/g);
        empIndex = inpName.replace(/\D+/g, '');

    obj[empIndex] = obj[empIndex] || {};
    obj[empIndex][name] = $(itm).val();
});

jsfiddle