Question

I have a HTML textbox in which users will enter the number of forms it requires and that number of forms will be shown to the user.

<label>No of Applicant</label><input type="text" class="form_input" id="applicant" value="1" onchange="addevent();"/></div>

The function addevent() is:

function addevent(){
var x=document.getElementById('applicant').value;

for(i=1;i<x;i++)
{
    var ts=document.getElementById('holder');
    var newdiv = document.createElement('div');

    var p=i+1;            // Form 1 is default, must exist
    if(p==1)
    {
        var no = p+' st';
    }
    else if(p==2)
    {
        var no = p+' nd';
    }
    else if(p==3)
    {
        var no = p+' rd';
    }
    else
    {
        var no = p+' th';
    }

        newdiv.innerHTML='<div class="form_row"><p>New Form number'+no+'</p></div>';
        ts.appendChild(newdiv);
    }


}   

And the above script working nicely. But if the user re enters the form he wants, the number of form is added to the previous forms. ie if previously he entered 2 forms, then he re enters 3 forms, total number of forms is now 5. So I want to know is there any way so that I can remove the divs that are created before creating new divs.

Was it helpful?

Solution

remove it before append

 ts.find('.form_row').remove();
 ts.appendChild(newdiv);

OTHER TIPS

This modification adds missing and removes redundant divs:

function addevent() {
    var x = parseInt(document.getElementById('applicant').value, 10);
    if (x<1) { x=1; }
    var ts = document.getElementById('holder');
    var divs = $(ts).children('.form_row');
    if (x < divs.length) {
        divs.each(function (i) {
            if (i >= x) {
                $(this).remove();
            }
        });
        return;
    }
    for (i = divs.length; i < x; i++) {
        var newdiv = document.createElement('div');
        var p = i + 1; // Form 1 is default, must exist
        /*if (p == 1) {
            var no = p + ' st';
        } else*/
        if (p == 2) {
            var no = p + ' nd';
        } else if (p == 3) {
            var no = p + ' rd';
        } else {
            var no = p + ' th';
        }
        newdiv.className = 'form_row';
        newdiv.innerHTML = '<p>New Form number' + no + '</p>';
        ts.appendChild(newdiv);
    }
}

http://jsfiddle.net/BqFEN/4/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top