create / remove text fields live in your html form

//Hint: i tried it on Jquery 1.7.1 and it worked !
//Hint: do not forget to add Jquery to your page !

$(document).ready(function() {

    //bader: set how many fields you need
    var MaxFields = 5;
    //bader: set the labelname
    var labelField = "Class: ";
    //bader: set the alert message
    var AlertMsg = "No More than ";


    //bader : code here     
    var counter = 1;


    //bader: here we add fields    
    $('#add').click(function() {

        
        if (counter > MaxFields) {
            alert(AlertMsg + MaxFields);
            return false;
        }

        $('#text').add('<div id="div' + counter + '"><label for="add">' + labelField + counter + ':  </label><input type="text" maxlength="50" value="" /></div>').appendTo(document.body);
        counter++;

    });

    //bader: here we delete fields
    $('#remove').click(function() {

        if (counter == 0) {

            alert("No More classes to remove");
counter = 1;            
            return false;       
            
        }

       
        
            
        $('#div' + counter).remove();
        counter--;
            
        


    });

});?


/* Add this to your html form
<input type="button" name="add" id="add" value="add" />
<input type="button" name="remove" id="remove" value="remove" /><br/>
*/

/* try demo here

http://jsfiddle.net/T3tUq/168/

*/

Leave a Reply