Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add/Remove Input Fields Dynamically with jQuery

I am looking to add and remove duplicate input fields using Jquery-

This is my HTML:

<div class="col-sm-9">
    <div class="input_wrap">
        <div><input type="text" name="text[]" class="form-control"></div>   

        // **** Here I want to add div using Jquery **** //

        <button class="add_field_button btn btn-info">Add More Subcategory</button>
    </div>
</div>

This is my Jquery:

var wrapper         = $(".input_wrap"); 
var add_button      = $(".add_field_button"); 

$(add_button).click(function(e){ 
  e.preventDefault();
  $(wrapper).prepend('<div><input type="text" name="text[]" class="form-control"><a href="#" class="remove_field">Remove</a></div>'); //add input box
});

When I using this Jquery its always add div below the .input_wrap DIV. But I want to add DIV to the place I have shown in my HTML Code.

UPDATE: This is the way I want to get enter image description here Hope somebody may help me out. Thank you.

like image 853
user3733831 Avatar asked Apr 20 '15 13:04

user3733831


3 Answers

You can use the after key

var wrapper = $(".input_wrap>div");
var add_button = $(".add_field_button");

$(add_button).click(function (e) {
    e.preventDefault();
    $(wrapper).after('<div><input type="text" name="text[]" class="form-control"><a href="#" class="remove_field">Remove</a></div>'); //add input box
});

Fiddle

Edit

Fiddle

Updated the fiddle to also include the remove functionallity

Created a new Fiddle Demo

I made a couple of small changes , the most important one is the

var el = $('.input_wrap div:last');

so that will basically get the last added div and then we will add the new div right after it.

$(el).after(newAdd);
like image 73
R4nc1d Avatar answered Nov 03 '22 19:11

R4nc1d


<div class="col-sm-9">
    <div class="input_wrap">
        <div><input type="text" name="text[]" class="form-control"></div>   

        <div class="more-data"></div> 

        <button class="add_field_button btn btn-info">Add More Subcategory</button>
    </div>
</div>

Your js

var wrapper         = $(".input_wrap"); 
var add_button      = $(".add_field_button"); 
var moredata      = $(".more-data"); 

$(add_button).click(function(e){ 
  e.preventDefault();
  moredata.html('<div><input type="text" name="text[]" class="form-control"><a href="#" class="remove_field">Remove</a></div>'); //add input box
});
like image 1
Kushal Avatar answered Nov 03 '22 19:11

Kushal


check the below jquery code

var add_button = $(".add_field_button");

        $(add_button).click(function(e){ 
          e.preventDefault();
          $(".input_wrap div:last").append('<div><input type="text" name="text[]" class="form-control"><a href="#" class="remove_field">Remove</a></div>'); //add input box
        });
like image 1
murtuzakothawala Avatar answered Nov 03 '22 21:11

murtuzakothawala