0

I have this simple code:

$("#additional-room").hide();

var numAdd = 0;
$("#add-room").click(function(e) {
    e.preventDefault();
    $("#additional-room").show("");

    if (numAdd >= 3) return;
    numAdd++;
    $('#additional-room').append('<p><input type="text" placeholder="room"></input><a href="#">delete</a></p>');
});

$("#additional-room a").click(function(e) {
    e.preventDefault();
    $(this).parent().remove();
    numAdd--;
    if (numAdd < 1) $("#additional-room").hide("");
});

it should add input field when required, however the remove fuction doesn't work. I'm sure it's a simple function but I don't understand why it doesn't work. Please help

Js fiddle: http://jsfiddle.net/qme9nq0b/1/

Samuel
  • 43
  • 7

1 Answers1

1

as p tag is added dynamically, you need to use event delegation:

$("#additional-room").on('click','a',function(e) {
    e.preventDefault();
    $(this).parent().remove();
    numAdd--;
    if (numAdd < 1) $("#additional-room").hide("");
});

Working Demo

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125