elow is the code i am using i am able to add new input box wen i click but it should stop adding based on the user input like no. of user-entered as 4 based on that add input box should stop
in below example:-$bookcount is user input field which comes from html input box
JavaScript
x
29
29
1
var i = 1;
2
3
if(i>$(bookcount))
4
{
5
$('#add').click(function()
6
{
7
i++;
8
$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="title[]" </td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
9
10
}});
11
12
$(document).on('click', '.btn_remove', function(){
13
var button_id = $(this).attr("id");
14
$('#row'+button_id+'').remove();
15
});
16
17
$('#submit').click(function(){
18
$.ajax({
19
url:"name.php",
20
method:"POST",
21
data:$('#add_name').serialize(),
22
success:function(data)
23
**strong text** {
24
alert(data);
25
$('#add_name')[0].reset();
26
}
27
});
28
});
29
Advertisement
Answer
Couple of issues to note:
- Assuming
bookcount
is found from$("#bookcount")
then you’ll need to get the.val()
and convert it to a number (as “10”<“2”) - Check against bookcount value inside the click event:
JavaScript
1
12
12
1
var i = 1;
2
var bookcount = $("#bookcount");
3
4
$('#add').click(function() {
5
if (i>(bookcount.val()*1)) {
6
// do nothing
7
return false;
8
}
9
10
i++;
11
$('#dynamic_field').append('<tr....
12
- as you also have a remove function, don’t forget to reduce
i
when removing
JavaScript
1
3
1
$(document).on('click', '.btn_remove', function(){
2
--i;
3
(in this case, I recommend something other than i
, eg rowCount
).
You can also do away with i
(rowCount
) by querying how many rows have been created dynamically:
JavaScript
1
10
10
1
var bookcountinput = $("#bookcount");
2
3
$('#add').click(function() {
4
var rows = $("#dynamic_field tr").length;
5
if (rows > bookcountinput.val()*1)
6
return;
7
8
$('#dynamic_field').append('<tr....
9
});
10