Reputation: 2612
I used this approach (https://dotnetfiddle.net/UjxtUW) to create a dynamic table in a MVC view.
The cells in the table has textbox and some text boxes values are populated via jQuery UI dialog. The code to open corresponding dialog box is,
$("#invItemsTable").on('click', 'td', function () {
var cIndex = $(this).index();
var $tr = $(this).closest('tr');
rowIndex = $tr.index();
if (cIndex == 7)
$("#dlAccCode").dialog("open");
else if (cIndex == 0)
$("#mdGrnList").dialog("open");
else if (cIndex == 5)
$("#dlTaxCode").dialog("open");
});
When the user selects a record in the dialog box, the CODE of that particular record is set to the table cell value by,
$("#AccCodeTable").delegate("input[type='radio']", "change", function (){
var $this = $(this);
$('#invItemsTable [id$=txtAccCode]').slice(rowIndex).val($this.val());
$('#dlAccCode').dialog("close");
});
The problem is if there are 5 rows in the table and if I change the 'CODE' of 3rd record, then 4th and 5th also updated with the same value.
This below code is also not working.
$('#invItemsTable tr:eq(' + rowIndex + ') td:eq(5)').val($this.val());
Please advice, if there is any way to set the text box value using column index and row index of the table.
Thanks.
Upvotes: 1
Views: 6370
Reputation: 2834
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('td').click(function () {
$('#txt').val($(this).text())
});
$('#btnset').click(function () {
var rowIndex = 1;
$('#invItemsTable tr:eq(' + rowIndex + ')').find('td:eq(5)').text($('#txt').val());
});
});
</script>
<body>
<input type="button" id="btnset" value="SetContent"/>
<input type="text" id="txt"/>
<table style="width:50%" id="invItemsTable">
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>11</td>
<td>22</td>
<td>33</td>
<td>44</td>
<td>55</td>
<td>66</td>
</tr>
</table>
</body>
</html>
Upvotes: 3
Reputation: 1190
use nth-child :
$('#invItemsTable tr:nth-child(' + rowIndex + ') td:nth-child(5)').val($this.val());
Upvotes: 0
Reputation: 2810
The problem is with your slice
statement. Slice takes 2 parameters, start
and end
which define the first and last indexes of items you wish to select from the array. If end
is omitted, slice will return all array elements from start
index to the end of the array. You need to define end
if you only want one element.
Change:
$('#invItemsTable [id$=txtAccCode]').slice(rowIndex).val($this.val());
To:
$('#invItemsTable [id$=txtAccCode]').slice(rowIndex, rowIndex + 1).val($this.val());
Upvotes: 0