1

So I'm creating a simple javascript program that allows me to add text boxes and a remove button that when clicked removes the button and the text box next to it:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>

<div id="space">
<div>
    <input type="text" class="in"/>
    <button class="btn" id="1">Remove</button>
</div>
</div>
<button id="add">Add</button>
<br/>
<button id="cacl">Calculate</button>
<br/>
<div id="container">
</div>
</body>
</html>

And here is the script

 $(function () {
    var i=2;
    $("#add").click(function () {
        $("#space").append('<div><input type="text" class="in"/> <button class="btn" id="'+i+'">Remove</button> <br/></div>');
        i++;
    });

    $(".btn").on('click', function () {
        console.log("OK");
        $(this).parent().remove();
    })
});

However when I click on the remove button nothing happens it doesn't even log "OK".

Any ideas?

David Mathers
  • 163
  • 2
  • 7

2 Answers2

0

Use $("#space").on('click', '.btn', function() { for dynamic event delegation (to present or future elements). jQuery docs .on()

$(function() {
  var i = 2;
  $("#add").click(function() {
    $("#space").append('<div><input type="text" class="in"/> <button class="btn" id="' + i + '">Remove</button> <br/></div>');
    i++;
  });

  $("#space").on('click', '.btn', function() {
    console.log("OK");
    $(this).parent().remove();
  })
});
<div id="space">
  <div>
    <input type="text" class="in" />
    <button class="btn" id="1">Remove</button>
  </div>
</div>

<button id="add">Add</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Another way is to add the listener to the Remove button at creation.
(Notice that in this case the already present max ID is 45)

var App = App || {

  /**
   * Get and store maximal button ID already present in #space
   */
  spaceButtonId: $("#space").find(".btn").get().reduce((id, el) => {
      return Math.max(id, el.id)
  }, 0),
  
  /**
   * Remove Field
   */
  removeSpaceField() {
      console.log("REMOVED ID: "+ this.id);
      $(this).closest(".field").remove();
  },
  
  /**
   * Create Field
   */
  createSpaceField() {
      App.spaceButtonId++;
      console.log("CREATED ID: "+ App.spaceButtonId);
      
      return $("<div/>", {
        "class": "field",
        appendTo: "#space",
        prepend: "<input type='text' class='in'>",
        append: $("<button/>", {
          id: App.spaceButtonId,
          "class": "btn",
          text: "Remove",
          type: "text",
          on: { click: App.removeSpaceField }   // For dynamically created elements
        })
      });
  }

};


/**
 * DOM ready and $ alias secured stuff:
 */
jQuery(function( $ ) { 

  $("#add").on('click', App.createSpaceField );
  $(".btn").on('click', App.removeSpaceField ); // For already present elements
  //  (no need to dynamically delegate since handled by App at button creation)

});
<div id="space">
  <div class="field"> <!-- P.S: ADD CLASS TO WRAPPER FIELD -->
    <input type="text" class="in"><button class="btn" id="1">Remove</button>
  </div>
  <div class="field">
    <input type="text" class="in"><button class="btn" id="45">Remove</button>
  </div>
</div>

<button id="add">Add</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
-1

If you just want to remove the REMOVE button and the text area. just use the code below:

$(function () {
    var i=2;
    $("#add").click(function () {
        $("#space").append('<div><input type="text" class="in"/> <button class="btn" id="'+i+'">Remove</button> <br/></div>');
        i++;
    });

    $(".btn").click(function () {
        $(".in, .btn").hide();
    });
});
agrm
  • 3,735
  • 4
  • 26
  • 36
jun drie
  • 860
  • 7
  • 14
  • 1
    **This is so wrong**. 1. Newly created `.btn` don't have any click listener. 2. on a single `.btn` element click you're **hiding** (???) **all** `.in` **and** `.btn` in the whole page 3. you're **hiding** instead of **removing**. 4. after all those operations you have `
    ` wrappers as left-over
    – Roko C. Buljan Dec 26 '17 at 01:40