I have this code:
$(function() {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 1;
$('#addScnt').live('click', function() {
$('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt_' + i + '" value="" placeholder="Input Value" /></label> <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;
});
});
input {
padding: 5px;
border: 3px solid #999;
border-radius: 8px;
margin-bottom: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<button id="addScnt" style='margin-bottom: 15px;'>Add (limit 5)</button>
<div id="p_scents">
<p>
<label for="p_scnts"><input type="text" id="p_scnt" class="p_scnt" size="20" name="p_scnt" value="" placeholder="Input Value" /></label>
</p>
</div>
I want to limit the creation of new inputs to 5 and create a unique id for each of them as they are generated, something like:
#myid1
#myid2
#myid3
#myid4
#myid5
This is a reproducible example only, I will need more fields for my real case.
$(function() {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 1;
$('#addScnt').on('click', function() {
if (i <= 4) { // 5 inputs limit
$('<p><label for="p_scnts"><input type="text" id="p_scnt_' + i + '" class="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label> <a href="#" class="remScnt">Remove</a></p>').appendTo(scntDiv);
i++;
}
return false;
});
$(document).on('click', '.remScnt', function() {
if (i > 2) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
But nothing else works. How to limit the number of entries created and assign a unique id to each of them?
2
Answers
jQuery.size()
has been removed with version 3.0. It has been replaced withjQuery.length
. I changed line three of your code and now it works, as demonstrated below:I fixed the obvious bug with possibly repeating
id
s. It is just a quick fix, but it will guarantee unique IDs.Adding to the question based on Wimanicesir’s comments below the answer
This Solution also does not use jQuery incase you wanted to see a different approach to the problem
Shown in the snippet all functionality is generated using plain vanilla java script
I’ve also added the containers ID to be displayed so you can see that they all have unique identifiers regardless of what one is removed
All that is done is using one counter that increases infinitely to use as the ID and one counter that only increases to 5 to use as the count of current inputs, the
MAX
value can be changed to allow for more inputs