JQuery - Find textbox values โโin table through $ .each loop
I have one HTML table ... This first row of HTML table is static, when they click one (+) button, rows are added dynamically, user wants to delete one row, he click one (-) means the current row is deleted.
Each line contains 4 text boxes. My JQuery code is below ..
var FirstName;
var LastName;
var Email;
var PhoneNumber;
$("#tableId tr").find('fieldset').each(function (i) {
FirstName =FirstName +','+ $("#txtFirstName" + (i + 1) + "").val();
LastName =LastName +','+ $("#txtLastName" + (i + 1) + "").val();
Email =Email +','+ $("#txtEmail" + (i + 1) + "").val();
PhoneNumber = PhoneNumber+','+ $("#txtPhoneNumber" + (i + 1) + "").val();
});
I am setting the id of the textboxes dynamically, its working, but when the user deletes one line, I cannot get the value of the textboxes based on the Id.
How do I get the values โโof text boxes?
+3
source to share
6 answers
I am using an index to access four text fields. Also added $ fieldset parameter as context.
$("#tableId").find('tr fieldset').each(function (i) {
var $fieldset = $(this);
FirstName =FirstName +','+ $('input:text:eq(0)', $fieldset).val();
LastName =LastName +','+ $('input:text:eq(1)', $fieldset).val();
Email =Email +','+ $('input:text:eq(2)', $fieldset).val();
PhoneNumber = PhoneNumber+','+ $('input:text:eq(3)', $fieldset).val();
});
+4
source to share
Assuming your table looks something like this:
โ<table>
<tr>
<td>
<input type="text" class="firstName" value="foo1">
<input type="text" class="lastName" value="ba1r">
</td>
</tr>
<tr>
<td>
<input type="text" class="firstName" value="foo2">
<input type="text" class="lastName" value="bar2">
</td>
</tr>
</tableโโโโโโโโโโโโโโโโโโโโโโโโโโ>โโโโ
here's a snippet that might work (it might need to be modified to suit your needs)
$(function() {
//storage
var data = {
firstName : [], lastName : []
}
//loop through the tr's
$('table tr').each(function() {
//look for the fields firstName and lastName in the tr
//get their values and push into storage
data.firstName.push($('.firstName', this).val());
data.lastName.push($('.lastName', this).val());
});
//view the data in the console
console.log(data);
//if you prefer the comma separated data
var firstName = data.firstName.join(',');
var lastName = data.lastName.join(',');
});โ
+3
source to share