Reputation: 313
I have a Jquery form set up where I can add and remove fields: http://jsfiddle.net/beehive/TLJGb/
I don't want to be able to add more than 10 fields on this form. How can I accomplish this?
$(function() {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 1;
$('#addScnt').live('click', function() {
$('<p id="yum">beets ' + i + ' <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);
i++;
return false;
});
$('#remScnt').live('click', function() {
if (i > 2) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
html:
<h2><a href="#" id="addScnt">Add Another</a></h2>
<div id="p_scents">
<p id="yum">
beets
</p>
</div>
Upvotes: 0
Views: 219
Reputation: 831
Just wrap the code that adds a new field in #addScnt's click handler in an if statement that checks if i is less than or equal to 10.
Or, in other words:
$('#addScnt').live('click', function() {
if (i <= 10) {
$('<p id="yum">beets ' + i + ' <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);
i++;
}
return false;
});
Upvotes: 0
Reputation: 4229
Add the following if statement to your code...
$('#addScnt').live('click', function() {
if ($(".item", addScnt).length < 9) {
$('<p class="item" id="yum">beets ' + i +' <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);
i++;
}
return false;
});
First I added a class to the items so I can detect them. Then I can count if there are less than 9 (+ the one you already had makes 10)
Here is the Fiddle
Upvotes: 5