Below is the tested code to Add/Remove Input Fields Dynamically with jQuery
HTML:
1 2 3 4 | < div class = "input_fields_wrap" > < button class = "add_field_button" >Add More Fields</ button > < div >< input type = "text" name = "mytext[]" ></ div > </ div > |
Script:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | jQuery(document).ready( function () { var max_fields = 10; //maximum input boxes allowed var wrapper = jQuery( ".input_fields_wrap" ); //Fields wrapper var add_button = jQuery( ".add_field_button" ); //Add button ID var x = 1; //initlal text box count jQuery(add_button).click( function (e){ //on add input button click e.preventDefault(); if (x < max_fields){ //max input box allowed x++; //text box increment jQuery(wrapper).append( '<div><input type="text" name="mytext[]"><a href="#" class="remove_field">Remove</a></div>' ); //add input box } }); jQuery(wrapper).on( "click" , ".remove_field" , function (e){ //user click on remove text e.preventDefault(); jQuery( this ).parent( 'div' ).remove(); x--; }) }); |
Note: Make sure, jQuery library has been included for the page.
Enjoy the day :) :)
No comments:
Post a Comment