0

html code

<div id="add-code">
<input type="text" class="code">
</div>
<a id="new-code"></a>

java script code

<script>
$(document).ready(function(){$("#new-code").click(function(){$("#add-code").append(`<input type="text" class="code">`)
});
$(".code").blur(function(){$(this).remove()})
})
</script>

here I have made a on click function for my tag for adding more input fields and blur function on code class for removing that input field but as I add more fields, the new added input fields do not support blur function

Ayush Gupta
  • 27
  • 1
  • 5
  • 1
    Have you tried using [.each()](https://api.jquery.com/each/)? – dale landry Jan 30 '22 at 07:35
  • 3
    None of the answers provided here show the most elegant solution to your problem, which is event delegation. **Also every solution presented here keeps adding new listeners to all `.code` elements regardless of whether they already have a listener or not, which is *really* bad.** – connexo Jan 30 '22 at 08:43

2 Answers2

1

You were actually very close. You were forgetting to add the event listener to the new elements when you were creating them.

I have corrected your function here

$("#new-code")
.click(function(){
    $("#add-code").append(
        $(`<input type="text" class="code">`).blur(function(){$(this).remove();})
    );
});

$(".code")
.blur(function(){
    $(this).remove();
});

Because these elements were created after your JavaScript loaded they never get the event listener. Therefore when we create the new elements we must bind the event listener to them before appending to the container.

staticBanter
  • 144
  • 4
  • 2
    Your code keeps adding new listeners to all `.code` elements regardless of whether they already have a listener or not. – connexo Jan 30 '22 at 08:47
  • This is actually a valid concern and i deleted the post as stop spreading bad code. I hope the revised answer is more sufficient as it directly binds the event listener to the new element. Thank you for your input it was a foolish error and I'm a little embarrassed t.b.h. – staticBanter Jan 30 '22 at 23:14
0

Because blur event listener is only called once, so it's active only on the currently existing inputs.
You need to call it each time you append a new input like this:

$(document).ready(function () {
  $("#new-code").click(function () {
    $("#add-code").append(`<input type="text" class="code">`);
    
    $(".code").last().blur(function () {
      $(this).remove();
    });
  });
});

Working example => https://codepen.io/moaaz_bs/pen/NWwGzvy?editors=1010

Moaaz Bhnas
  • 1,010
  • 7
  • 18
  • 36