Currently, I have an input element that has the capability to clear its value when a button is clicked. Additionally, this input can dynamically add or remove input elements. However, I am facing an issue where after adding an input element, the clear button does not work.
Here is what I have attempted so far:
// JavaScript code for adding and removing input elements
var counter = 1,
custom = $('#custom');
$(function() {
$('#add_field').click(function() {
counter += 1;
var newRow = $('<div class="row' + counter + '"><span class="wrap_input"><input id="exception_' + counter + '" name="" type="text"><button class="btn_clear">clear</button><button class="remove-text-box">Remove</button></span></div>');
custom.append(newRow);
(function(index) {
newRow.find('.remove-text-box').click(function() {
custom.find('.row' + index).remove();
});
})(counter);
});
});
// JavaScript code for clearing input value
$('.wrap_input').each(function() {
var $inp = $(this).find("input"),
$cle = $(this).find(".btn_clear");
$inp.on("input", function(){
$cle.toggle(!!this.value);
});
$cle.on("touchstart click", function(e) {
e.preventDefault();
$inp.val("").trigger("input").focus();
$inp.change();
});
});
.btn_clear { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="add_field" href="#">add input</button>
<div id="custom">
<span class="wrap_input">
<input type="text" value="">
<button class="btn_clear">clear</button>
</span>
</div>
The first input is functioning correctly, however, after adding another input element, the clear button does not appear.
Please assist me in resolving this issue.