Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove input by Javascript

var i = 1;
$('.button').click(function() {
  $('<br/><input name="name' + (++i) + '" type="text"/>').insertBefore(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
  <input name="name1" type="text" /><button class="button">+</button>
</div>

How can I place a button with [ + ] plus button, and when I click on it. button remove that field.

like image 453
Hamza Khan Avatar asked Aug 10 '15 07:08

Hamza Khan


2 Answers

You can do something like this

var i = 1;
$('.button').click(function() {
  $('<br/><input name="name' + (++i) + '" type="text"/><button class="button1">-</button>').insertBefore(this);
});
$(document).on('click', '.button1', function() {
  $(this)
    .prev('input').remove()
    //removing input field
    .end().prev('br').remove()
    //removing br tag
    .end().remove();
  //removing the button
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
  <input name="name1" type="text" />
  <button class="button">+</button>
</div>
like image 36
Pranav C Balan Avatar answered Sep 18 '22 10:09

Pranav C Balan


Just add a new button template into your HTML string and a wrapping <div> to identify the row. Then use event delegation to bind onto the dynamically created remove buttons:

var i = 1;
$('.button').click(function() {
  // Wrap each row in a div. Won't need a <br> to create a line break and it's styleable
  $('<div><input name="name' + (++i) + '" type="text"/><button class="remove">-</button></div>').insertBefore(this);
});
// We need to use event delegation here, as the remove buttons are dynamically generated
$(document).on("click", ".remove", function() {
  // Remove the parent, which is the rows <div> element
  $(this).parent().remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="button">+</button>
like image 175
CodingIntrigue Avatar answered Sep 18 '22 10:09

CodingIntrigue