Hamza Khan
Hamza Khan

Reputation: 191

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.

Upvotes: 6

Views: 1519

Answers (4)

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

var i = 1;
$('.button').click(function () {
    $('<input name="name' + (++i) + '" type="text"/><button class="remove">remove</button><br>').prependTo($(this).closest('div'));
});

$("div").on("click", ".remove",function () {
    $(this).prev("input").add($(this).next("br")).add($(this)).remove();
});

DEMO

Upvotes: 2

Pranav C Balan
Pranav C Balan

Reputation: 115222

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>

Upvotes: 3

CodingIntrigue
CodingIntrigue

Reputation: 78525

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>

Upvotes: 7

Andre Andersen
Andre Andersen

Reputation: 1211

I would highly recommend looking at using Knockout, Angular, or something like that. They're implementations of the MVVM pattern, which is quite useful in your scenario.

Here is a sample of how Knockout.js works, and directly correlates to your problem scenario.

Upvotes: 1

Related Questions