我有一个输入按钮,每次单击该按钮都会生成一个新表单,但是我一直努力在10次单击后禁用它,因为我不希望用户能够创建无限数量的表单。在这里:
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" />
这是我尝试过的:
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);
}
答案 0 :(得分:1)
将if语句包装在整个函数中,它应该可以按预期工作。
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)
}
}
答案 1 :(得分:1)
要执行此操作是要删除还是禁用按钮?
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();
}
}
或显示提醒-您选择