I am working on a requirement, where I need to push numbers in text boxes to an array. The text boxes are in the 2nd cell in the table row and 3rd cell is a date picker.
The code snippet below is giving me all text field values along with date values in array. I need only the values of the text fields to that array. Please help me with solution.
var NumbersArray = $('#myTable input[type=text]').map(function() {
return this.value;
}).get();
console.log(NumbersArray);
This piece of code below is also not working:
var secondCellContents = [],
$('#myTable tbody tr').each(function() {
var $secondCell = $(this).children('td').eq(1).text(),
secondCellContent = $secondCell.text();
secondCellContents.push(secondCellContent);
});
console.log(secondCellContents);
You can do the same thing for 2nd cell also like:
var secondCellContents = $('#myTable tbody tr').map(function() {
return $('td:eq(1)', this).val();
}).get();
console.log(secondCellContents);
Also, the .val()
method is primarily used to get the values of form elements such as input, select and textarea and .text()
is used to get the combined text contents of each element. The .text()
method returns the value of text and CDATA nodes as well as element nodes.
This is how to make it work with your own code.
$(document).ready(function(){
var NumbersArray = $('#myTable td:nth-child(2) input[type="text"]').map(function() {
return $(this).val();
}).get();
console.log(NumbersArray);
//OR
var secondCellContents = [];
$('#myTable tbody tr').each(function () {
var $secondCell = $(this).children('td:eq(1)');
secondCellContent = $secondCell.find('input').val();
secondCellContents.push(secondCellContent);
});
console.log(secondCellContents);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='myTable'>
<tbody>
<tr>
<td>Row 1</td>
<td><input type='text' value="1" /></td>
<td></td>
</tr>
<tr>
<td>Row 2</td>
<td><input type='text' value="2" /></td>
<td></td>
</tr>
<tr>
<td>Row 3</td>
<td><input type='text' value="3" /></td>
<td></td>
</tr>
</tbody>
</table>
</div>