仅附加一次文本框

时间:2015-01-20 06:50:14

标签: javascript html

我有一个功能复选框,附加一个文本框onclick ..现在问题是每次我点击复选框出现一个新的文本框,如果我点击复选框说10次我得到10个文本框..我想停止它和单击后无法使用禁用文本框,因为有一个功能在禁用文本框时无法正常工作。任何有关这方面的帮助将不胜感激。

<input onClick="myFunction();" id="demoteTask" name="demoteTask" type="checkbox"/>&nbsp;<label for"demoteTask_cbx">Demote to Child</label>

<span id="DemoteContainer"></span>

<script>
function myFunction() {
var span = document.createElement('SPAN');
span.innerHTML = '<input id="parent" name = "parent" type="textbox" />';
document.getElementById("DemoteContainer").appendChild(span);
}
</script>

我想实现这样的目标:

<script>
var tmp=1;
function myFunction() {
if(tmp%2==1)
{
var span = document.createElement('SPAN');
span.innerHTML = '<input id="parent" name = "parent" type="textbox" />';
document.getElementById("DemoteContainer").appendChild(span);
tmp++;
}
else
{
var d = document.getElementById("DemoteContainer");
var d_nested = document.getElementById("parent");
var throwawayNode = d.removeChild(d_nested);
tmp++;
}
}
</script>

4 个答案:

答案 0 :(得分:3)

您可以在添加文本框之前检查元素(文本框)是否存在,如:

function myFunction() {
    //check if text box with id "parent" exists, add if doesn't
    if( !document.getElementById("parent") ) {
        var span = document.createElement('SPAN');
        span.innerHTML = '<input id="parent" name = "parent" type="textbox" />';
        document.getElementById("DemoteContainer").appendChild(span);
    }
}

function myFunction() {
    //check if text box with id "parent" exists, add if doesn't
    if( !document.querySelector("#DemoteContainer input#parent") ) {
        var span = document.createElement('SPAN');
        span.innerHTML = '<input id="parent" name = "parent" type="textbox" />';
        document.getElementById("DemoteContainer").appendChild(span);
    }
}

答案 1 :(得分:1)

如果您不介意每次单击时再次生成文本框,请使用innerHTML替换容器的整个内容,而不是appendChild:

document.getElementById("DemoteContainer").innerHTML = '<input id="parent" name = "parent" type="textbox" />';

答案 2 :(得分:1)

将脚本替换为以下脚本: -

<script>
function myFunction() {
    var elem = document.getElementById("parent");
    if(elem != null)
elem.parentNode.removeChild(elem);
var span = document.createElement('SPAN');
span.innerHTML = '<input id="parent" name = "parent" type="textbox" />';
document.getElementById("DemoteContainer").appendChild(span);
// document.getElementById("demoteTask").disabled = true;
}
</script>

答案 3 :(得分:0)

&#13;
&#13;
<input onClick="myFunction();" id="demoteTask" name="demoteTask" type="checkbox"/>&nbsp;<label for"demoteTask_cbx">Demote to Child</label>

<span id="DemoteContainer"></span>

<script>
function myFunction() {
  var checkBox = document.getElementById('demoteTask');
  if (!checkBox.checked) {
    document.getElementById("parent").remove()
  } else {
    var span = document.createElement('span');
    span.innerHTML = '<input id="parent" name = "parent" type="textbox" />';
    document.getElementById("DemoteContainer").appendChild(span);
  }
}
  
  
  
</script>
&#13;
&#13;
&#13;