I have a form/table that is dynamically altered via JS by adding/removing rows (form inputs). I want to create a column that counts the number of rows, so I tried using,
$("#rowcount:last").replaceWith( "<td>" + newNum + "</td>" );
to change the counter columns last element to the new number, but the ‘:last’ selector doesn’t seem to work in this case. Here is my code for reference (sorry for the ugliness of my form. I tried to make it look as pretty as I could, but because of my limited experience, it still looks like it was slapped on the wrong side at birth):
<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script src="jquery.maskedinput.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#btnAdd').click(function() {
var num = $('.ccinput').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
// create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
// insert the new element after the last "duplicatable" input field
$('#input' + num).after(newElem);
$("#rowcount").replaceWith( "<td>" + newNum + "</td>" );
// enable the "remove" button
$('#btnDel').attr('disabled','');
$("*#date").mask("99/99/9999");
// business rule: you can only add 20 names
if (newNum == 20)
$('#btnAdd').attr('disabled','disabled');
});
$('#btnDel').click(function() {
var num = $('.ccinput').length; // how many "duplicatable" input fields we currently have
$('#input' + num).remove(); // remove the last element
// enable the "add" button
$('#btnAdd').attr('disabled','');
// if only one element remains, disable the "remove" button
if (num-1 == 1)
$('#btnDel').attr('disabled','disabled');
});
$("*#date").mask("99/99/9999");
});
</script>
</head>
<body>
<form method="post" action="<?php echo htmlentities($PHP_SELF); ?>">
<table border="1" cellspacing="0">
<tr>
<th></th>
<th># (last four digits)</th>
<th>Amount</th>
<th>Approval</th>
<th>Date Received</th>
</tr>
<tbody>
<tr id="input1" class="ccinput">
<td id="rowcount"> 1 </td>
<td> <input id="cnum" type="text" name="cc_num[]" maxlength="4" /> </td>
<td> <input id="camnt" type="int" name="cc_amnt[]" /> </td>
<td> <input id="appr" type="text" name="cc_app[]" maxlength="10" /> </td>
<td> <input id="date" type="text" name="cc_date[]" /> </td>
</tr>
</tbody>
</table>
<div>
<input type="button" id="btnAdd" value="Add" />
<input type="button" id="btnDel" value="Remove" />
</div>
<input type="submit" value="Submit" name="submit" />
</form>
</body>
</html>
You can use the
:lastselector:or instead of
replaceWith()you can try:DEMO