Learn free online HTML5, javascript, and jquery Tutorials by Examples

Friday, 19 December 2014

Add/Remove Input Fields Dynamically with jQuery

<script src="jquery.min.js"></script>
<script>
    $(document).ready(function() {
    var max_fields      = 10;
    var wrapper         = $(".input_fields_wrap"); 
    var add_button      = $(".add_field_button"); 
  
    var x = 1;
    $(add_button).click(function(e){ 
        e.preventDefault();
        if(x < max_fields){ 
            x++;
            $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
        }
    });
  
    $(wrapper).on("click",".remove_field", function(e){
        e.preventDefault();
        $(this).parent('div').remove();
        x--;
    })
});
</script>

<div class="input_fields_wrap">
    <button class="add_field_button">Add More Fields</button>
    <div><input type="text" name="mytext[]"></div>
</div>

No comments:

Post a Comment