I am studing jquery to post input tables. All inputs need to be posted with their indexes. I am guessing that i cant use ids or classes of input elements to post values with cell location info. .Because Input tables are generated dynamically according to user answer.
For Example;
User enters '4' value to a question and a 3col 4row input table is generated.
<table>
<tr><td><input type="text"></td> <td><input type="text"></td> <td><input type="text"></td>
</tr>
<tr><td><input type="text"></td> <td><input type="text"></td> <td><input type="text"></td>
</tr>
<tr><td><input type="text"></td> <td><input type="text"></td> <td><input type="text"></td>
</tr>
<tr><td><input type="text"></td> <td><input type="text"></td> <td><input type="text"></td>
</tr>
</table>
And by using jquery handler i can store the values...
$(function () {
$("input").change(function() {
// save this.value() in an array.
array.push(this.value());
});
});
I stuck at this moment because i have to store values with their (x,y)indexes in the table. Shortly; values of this 2 dimension table must be converted to a 2dim. data array in server-side.
Something like...
$(function () {
$("input").change(function() {
array[this.col][this.row] = this.value();
});
});
To sum up;
Is it possible to get the location(col,row) of an element, which is inside a table?
You can use index() method as follows
$(function () {
$("input").change(function () {
var row = $(this).closest('tr').index(); //index of row
var col= $(this).closest('td').index(); //index of column
// your code
});
});
Try something like this:
$(function () {
var $rows=$('tr');/* refine if using column heading row to something like $('tr:gt(0)')*/
$("input").change(function() {
var $row=$(this).closest('tr');
var rowIndex=$rows.index($row);
var colIndex=$(this).parent().index();
/* do something with indexes*/
});
});
if you want store value of column and rows in array you can use a multidimensional array (array of arrays).
first of all you insert in default array other arrays that rapresent yuour rows and then when the field change you'll store data in array first data:rows second data column.
<script type="text/javascript">
$(document).ready(function(){
var array=[]
for(a=0;a<$('table tr').length;a++){
array[a]=[]
}
$("input").change(function() {
var val=$(this).val()
var row=$(this).parents('tr').index()
var column =$(this).parent('td').index()
array[row][column] = val
console.log(array)
});
})
</script>