Reputation: 197
i am trying to create dynamic textboxes. The textbox should be created only if the previous textbox is non-empty. So far i have done this
<!DOCTYPE html>
<html>
<head>
<script>
var i=0;
function myFunction()
{
var box = document.createElement("input");
box.type = "text";
var str=box+i;
if(i==0)
{
document.body.appendChild(box);
}
else if(document.getElementById('str').value!=0)
{
document.body.appendChild(box);
}
i++;
}
</script>
</head>
<body>
<input type="button" id="button" onclick="myFunction()" value="Show box" />
</body>
</html>
but str is not recognised as element id. Any help will be appreciated.
Upvotes: 0
Views: 91
Reputation: 14982
Your wrongs:
str = 'box' + i;
Forget to assign box.id = str
Use getElementById(str)
instead of getElementById('str')
Upvotes: 0
Reputation: 19294
var i = 0;
function myFunction() {
var lastInput = document.getElementById('box' + i);
if (!lastInput) {
// always put first input
document.body.appendChild(createInput(0));
} else if (lastInput.value != 0) {
// append another one only if previous input content is non-null
i++;
document.body.appendChild(createInput(i));
}
}
function createInput(i) {
var box = document.createElement("input");
box.type = 'text';
box.id = 'box' + i;
box.value = 0;
return box;
}
Upvotes: 1