新手在这里。我的目标是我想忽略输入类型的文本并通过单击按钮添加带有ID的复选框
<html>
<body>
Enter a Value <input type="text" id="prod" autofocus />
<p>
<input type="button" id="bt" value="Create Checkbox" onclick="createChk(prod)" />
</p>
<p id="container"></p>
</body>
<script>
var i = 1; // COUNTER, FOR CHECKBOX ID.
function createChk(obj) {
if (obj.value !== '') {
var chk = document.createElement('input'); // CREATE CHECK BOX.
chk.setAttribute('type', 'checkbox', 'button'); // SPECIFY THE TYPE OF ELEMENT.
chk.setAttribute('id', 'prodName' + i); // SET UNIQUE ID.
chk.setAttribute('value', obj.value);
chk.setAttribute('name', 'products');
var lbl = document.createElement('label'); // CREATE LABEL.
lbl.setAttribute('for', 'prodName' + i);
// APPEND THE NEWLY CREATED CHECKBOX AND LABEL TO THE <p> ELEMENT.
container.appendChild(chk);
container.appendChild(lbl);
obj.value = '';
document.getElementById(obj.id).focus();
i = i + 1;
}
}
</script>
</html>
在此处查看代码段:https : //www.encodedna.com/javascript/practice-ground/default.htm?pg=create_checkboxes_using_javascript1
我希望我已经正确理解了你的问题
不管文本输入值是什么,此代码都会添加一个复选框
所有被删除的是if
声明
<!DOCTYPE html>
<html>
<head>
<title>Add Checkbox Dynamically using JavaScript</title>
</head>
<body>
Enter a Value <input type="text" id="prod" autofocus />
<p>
<input type="button" id="bt" value="Create Checkbox" onclick="createChk(prod)" />
</p>
<p id="container"></p>
</body>
<script>
var i = 1; // COUNTER, FOR CHECKBOX ID.
function createChk(obj) {
var chk = document.createElement('input'); // CREATE CHECK BOX.
chk.setAttribute('type', 'checkbox'); // SPECIFY THE TYPE OF ELEMENT.
chk.setAttribute('id', 'prodName' + i); // SET UNIQUE ID.
chk.setAttribute('value', obj.value);
chk.setAttribute('name', 'products');
var lbl = document.createElement('label'); // CREATE LABEL.
lbl.setAttribute('for', 'prodName' + i);
// CREATE A TEXT NODE AND APPEND IT TO THE LABEL.
lbl.appendChild(document.createTextNode(obj.value));
// APPEND THE NEWLY CREATED CHECKBOX AND LABEL TO THE <p> ELEMENT.
container.appendChild(chk);
container.appendChild(lbl);
obj.value = '';
document.getElementById(obj.id).focus();
i = i + 1;
}
</script>
</html>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句