Search code examples
javascripthtmlif-statementtextarea

JavaScript script create only one textarea instead of 4


    <div id="textfelder"></div>
<script>
if (!document.getElementById('command1')) {
    string = '<input type="text" id="command1">';
    document.getElementById("textfelder").innerHTML = string;
    }
if (!document.getElementById('command2')) {
    string = '<input type="text" id="command2">';
    document.getElementById("textfelder").innerHTML = string;
    }
if (!document.getElementById('command3')) {
     string = '<input type="text" id="command3">';
     document.getElementById("textfelder").innerHTML = string;
    }
if (!document.getElementById('command4')) {
     string = '<input type="text" id="command4">';
     document.getElementById("textfelder").innerHTML = string;
    }
</script>

This only creates one textarea with the ID "command4". When I remove the last if-statement, the script will be create the textarea with the ID "command3" but the other textareas will be not created. Thanks! :D


Solution

  • Use += operator instead of =.

        <div id="textfelder"></div>
    <script>
    if (!document.getElementById('command1')) {
        string = '<input type="text" id="command1">';
        document.getElementById("textfelder").innerHTML += string;
        }
    if (!document.getElementById('command2')) {
        string = '<input type="text" id="command2">';
        document.getElementById("textfelder").innerHTML += string;
        }
    if (!document.getElementById('command3')) {
         string = '<input type="text" id="command3">';
         document.getElementById("textfelder").innerHTML += string;
        }
    if (!document.getElementById('command4')) {
         string = '<input type="text" id="command4">';
         document.getElementById("textfelder").innerHTML += string;
        }
    </script>