jquery code to add more and remove multiple input fields recursively

This code used to append more input fields and remove input fields recursively.

div with input fields to add more and remove

<div id="phone_number_form" class="hidden"> <p> Phone number : <input type="text" name="phone_number"> first name : <input type="text" name="firstname"> <input type="button" id="remove_phone_number" value="Remove"> </p> </div> <form> <p> <input type="button" value="Add phone number" id="add_phone_number"> </p> </form>



css to hide the class hidden of div

.hidden {
    display: none;
}
/* Bellow is completely unnecessary */
* {
font-family: Arial;
font-size: 13px;
}

javascript code with onlick to add more and remove input fields

$(document).ready(function(){
    var phone_number_form_index=0;
    $("#add_phone_number").click(function(){
        phone_number_form_index++;
        $(this).parent().before($("#phone_number_form").clone().attr("id","phone_number_form" + phone_number_form_index));
        $("#phone_number_form" + phone_number_form_index).css("display","inline");
        $("#phone_number_form" + phone_number_form_index + " :input").each(function(){
            $(this).attr("name",$(this).attr("name") + phone_number_form_index);
            $(this).attr("id",$(this).attr("id") + phone_number_form_index);
            });
        $("#remove_phone_number" + phone_number_form_index).click(function(){
            $(this).closest("div").remove();
        });
    }); 
});



Comments

Popular posts from this blog

Find pair of n numbers in php

php: nested if in select tag

yii framework simple shopping cart tutorial for beginners