I have a button when pressed creates new input bars and I would like those input bars to have unique ids, for example - textBar1, textBar2, textBar3 and so on.
I tried creating a variable outside of the function that has the value 0 and then inside the function add the value with +1 for each time the function runs but that doesn't work but instead it assigns the id textBar0 to every element that is created.
Does anyone have any suggestions on how to solve this?
Thanks in advance!
HTML
<label for='ingredient'></label>
<input id="textBar" class="textBar" type="name" name="ingredient">
<div id="textBarPosition"></div>
<div id="addRemoveContainer">
<input id="addBar" type="button" value="Add Ingredient">
JavaScript/jQuery
var counter = 0;
function createSector() {
var input = document.createElement('input');
input.setAttribute("id", 'textBar' + counter +1);
input.type = 'text';
input.name = 'name[]';
return input;
counter = 1;
}
var form = document.getElementById('textBarPosition');
document.getElementById('addBar').addEventListener('click', function(e) {
// step 1: create element and set opacity to 0.
var selector = $(createSector());
selector.fadeIn();
// step 2: append it to its parent.
$(form).append(selector);
$('#removeBar').click(function(){
$("input:last-child").remove(".textBar");
});
});
That is becaus you're not reassinging the changed value to counter
.
Use counter+=1
instead or just counter++
input.setAttribute("id", 'textBar' + counter++); // now it should work
What you were doing before was always add 1
to 0