Reputation: 11735
I have two columns in my table and the rows are created dynamically.
<table id ="datatable">
<tr>
<td>
<input type ="text">
</td>
<td>
<input type ="text">
</td>
</tr>
</table>
For each row, I want to get the value of each table and insert them in an object as follows.
var reading= new Object();
reading.Name = (column1).value
reading.Value = (column2).value
How can I do that?
Upvotes: 0
Views: 4175
Reputation: 9493
//fetching lines
$('table tr').each(function(){
var reading = new Object();
reading.name = $(this).find('td:first input').val();
reading.value= $(this).find('td:last input').val();
});
Updated: set error message if is empty
$('table tr').each(function(){
var reading = new Object();
name = $(this).find('td:first');
reading.name = name.find('>input').val();
if(reading.name == '')
{
name.append('<span>field empty</span>');
}
value = $(this).find('td:last');
reading.value = value.find('>input').val();
if(reading.value == '')
{
value.append('<span>field empty</span>');
}
});
Upvotes: 1
Reputation: 74560
You could use a selector that gets all the input types that are in table cells and then iterate through each of them using the each function:
// Get the selector.
var selector = $("#datatable tr td input[type='text']");
// Create the object.
var reading = {};
// Cycle through the inputs, attaching the properties.
selector.each(function (index, element) {
// If index is 0, then set the name property.
if (index === 0) reading.Name = $(this).val();
// If index is 1, set the value property.
if (index === 1) reading.Value = $(this).val();
});
Note, the selector doesn't have to be so exact. A simple selector such as #datatabe input
would work in this case as well (assuming all of your input types are text fields).
As for the code, it is heavily reliant on the positional value of the inputs, and that's not a good thing, as layout can easily be changed. Rather, you might want to attribute your input types with either the name or id attribute, or a custom data attribute (prefixed with "data-", this is an HTML 5 addition, but is valid for 4.01 strict), like so:
<table id ="datatable">
<tr>
<td>
<input name="Name" type ="text">
</td>
<td>
<input name="Value" type ="text">
</td>
</tr>
</table>
Then, you can change your code to be more flexible, getting the property name from the attribute value, like so:
// Get the selector.
var selector = $("#datatable tr td input[type='text']");
// Create the object.
var reading = {};
// Cycle through the inputs, attaching the properties.
selector.each(function (index, element) {
// Get the selector for the element.
var thisSelector = $(this);
// Set the value accoding to the name on the element.
reading[thisSelector.attr("name")] = thisSelector.val();
});
This way, you can add/remove properties and not have to change your code, as it reads from the attributes on the elements.
Upvotes: 0