Reputation: 349
I have an input button which generates a new form every everytime you click it but I'm struggling to disable it after 10 clicks as I don't want the user to be able to create an infinite amount of forms. Here it is:
var room = 1;
function add_fields() {
room++;
var objTo = document.getElementById("room_fileds");
var divtest = document.createElement("div");
divtest.innerHTML =
'<div class="control-group">' +
'<label class="control-label">Company</label>' +
'<div class="controls">' +
'<input class="input-border collection-input "id="company" name="company' +
room +
' "type="text" placeholder="Company">' +
"</div>" +
"</div>"
objTo.appendChild(divtest);
}
<div id="room_fileds">
<div class='label'>Drop off address:</div>
</div>
<input type="button" id="more_fields" class="btn mt-3 mb-2" onclick="add_fields();" value="Add More" />
Here's what I tried:
var room = 1;
function add_fields() {
if(room < 11){
room++
}
var objTo = document.getElementById("room_fileds");
var divtest = document.createElement("div");
divtest.innerHTML =
'<div class="control-group">' +
'<label class="control-label">Company</label>' +
'<div class="controls">' +
'<input class="input-border collection-input "id="company" name="company' +
room +
' "type="text" placeholder="Company">' +
"</div>" +
"</div>"
objTo.appendChild(divtest);
}
Upvotes: 0
Views: 126
Reputation: 51
Remove or disable button for make this action?:
var room = 1;
function add_fields() {
if(room < 11) {
room++
var objTo = document.getElementById("room_fileds");
var divtest = document.createElement("div");
divtest.innerHTML =
'<div class="control-group">' +
'<label class="control-label">Company</label>' +
'<div class="controls">' +
'<input class="input-border collection-input "id="company" name="company' +
room +
' "type="text" placeholder="Company">' +
"</div>" +
"</div>"
objTo.appendChild(divtest);
} else {
document.getElementById('more_fields').setAttribute('disabled', 'disabled');
//or
document.getElementById('more_fields').remove();
}
}
or show alert - your choose
Upvotes: 1
Reputation: 326
Wrap the if statement around the whole function and it should work as you expect.
var room = 1
function add_fields() {
if (room < 11) {
room++
var objTo = document.getElementById("room_fileds")
var divtest = document.createElement("div")
divtest.innerHTML =
'<div class="control-group">' +
'<label class="control-label">Company</label>' +
'<div class="controls">' +
'<input class="input-border collection-input "id="company" name="company' +
room +
' "type="text" placeholder="Company">' +
"</div>" +
"</div>"
objTo.appendChild(divtest)
}
}
Upvotes: 1