Reputation: 366
refer my below javascript code , how to count rows if i click add form and remove form, my reason is i want to do something like this :
*so the value will be dynamic when click "add form" the value(from count form) will be increase but when i click remove the value will be decrease.
<?php $totalrow=$count_from_rows_javascript; ?>
<label>Total Row</label>
<input type="text" name="total_row" id="total_row" value="<?php echo $totalrow; ?>"/>
My Javascript Code :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript">
(function($){
$countForms = 1;
$.fn.addForms = function(){
if ($countForms == 11 ) {
$("#mybutton").unbind("click");
return;
}
var myform = "<table>"+
" <tr>"+
" <td>Field A ("+$countForms+"):</td>"+
" <td><input type='text' name='fielda["+$countForms+"]'></td>"+
" <td>Field B ("+$countForms+"):</td>"+
" <td><textarea name='fieldb["+$countForms+"]'></textarea></td>"+
" <td><button>remove</button></td>"+
" </tr>"+
"</table>";
myform = $("<div>"+myform+"</div>");
$("button", $(myform)).click(function(){ $(this).parent().parent().remove(); });
$(this).append(myform);
$countForms++;
};
})(jQuery);
$(function(){
$("#mybutton").bind("click", function(){
$("#container").addForms();
});
});
</script>
</head>
<body>
<button id="mybutton">add form</button>
<div id="container"></div>
so any suggestion would be much appreciated! (i'm still newbie in javascript)
Thanks.
Upvotes: 0
Views: 516
Reputation: 26
I know how to transfer from PHP to javascript, but I'm not sure it's possible the other way around. You could use javascript to update that text field though.
Just add this line before $countForms++;
:
$("#total_row").val($countForms);
Upvotes: 1
Reputation: 41533
If you want to count the total number of rows you can use :
$('tr').length
If you want to count the number of rows only in your container, use :
$('tr','#container').length
You could add a certain class to the dynamically generated tables (a.k.a myform) to avoid confusion in selectors :
//...
myform = $("<div>"+myform+"</div>").addClass('my_class_name');
//...
And then safely count the rows as :
$('tr','.my_class_name').length
I'm sorry if this isn't the answer that you're hoping to get, but you weren't quite explicit.
If you want to update a field that's a bit different than counting rows.
As Neil suggested, the way to do that would be :
$("#total_row").val(newVal);
where newVal
is the new value that you want your input to have ( could be your $countForms
variable or one of my suggested count methods).
Upvotes: 1