April 6, 2012

Input texts go back to default value after click

Question by nunos

The form below is working as I want except for one thing. When I click the ‘Add’ link I the texts of all the textboxes go back to its default value like seen in the images. How can I fix it? Thanks.

before click:

first image

after click on ‘Add’:

second image

Code:

function addSection() {
    var str = '<div>' + 
                '<input type="text" name="composer" value="Compositor" />' + 
                '<input type="text" name="peca" value="Peca" size="40" />' + 
                '<input type="button" value="x" style="width: 26px" onclick="delSection(this)" /><br />' + 
            '</div>';

    document.getElementById("programa").innerHTML += str;
}

function delSection(field) {
    field.parentNode.outerHTML = "";
}

window.onload = addSection;

</script>
<fieldset>
    <legend>Programa</legend>
    <div id="programa">
    </div>
    <a href="#" onclick="addSection()" >Add</a><br />
</fieldset>
<input type="submit" value="Inscrever Aluno" name="submit" />

Answer by Starx

You can overcome this, using appendChild()

JS

function newSet() {
    var div = document.createElement("div");   

    var composer = document.createElement("input");
    composer.type="text";
    composer.value = "Compositer";

    var peca = document.createElement("input");
    peca.type = "text";
    peca.value = "Peca";

    var button = document.createElement("input");
    button.type = "submit"

    div.appendChild(composer);
    div.appendChild(peca);
    div.appendChild(button);

    return div
}

function addSection() {    
    document.getElementById("programa").appendChild(newSet());
}

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!