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
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.
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