Remove input by clicking times icon

Viewed 112

I have the following code which adds divs within a container (#subtask_container) via clicking a link (similar to Google Tasks):

HTML:

<p class="text-muted">
    <i class="fas fa-tasks mr-2"></i>
    <a href="#" id="add_subtask">Add subtasks</a>
</p>
<div id="subtask_container"></div>

JS (this successfully adds unique inputs within the subtask container div along with a clickable x after each input)

var i = 1
      $("#add_subtask").click(function () {
  $("#subtask_container").append('<input name="subtask'+i+'" class="mt-1" id="subtask'+i+'" placeholder="Enter subtask"><i class="fas fa-times ml-1 text-muted"></i><br>');
        i++;
});

What logic do I need to add to the x class to remove it's associated input?

I've tried

$('.fa-times').click(function(){
        $(this).prev('input').remove();
      });

but it doesn't seem to work...

Thanks!

2 Answers

The event handler gets attached to all elements that are on the page load. Since the icons are appended, the right way to do this would be the following:

var i = 1
$("#add_subtask").click(function () {
  $("#subtask_container").append('<div><input name="subtask'+i+'" class="mt-1" id="subtask'+i+'" placeholder="Enter subtask"><i class="fas fa-times ml-1 text-muted removeIcon"></i><br></div>');
  i++;
});

$(document).on('click', '.removeIcon', function(){
  $(this).parent().remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://kit.fontawesome.com/a076d05399.js"></script>

<p class="text-muted">
    <i class="fas fa-tasks mr-2"></i>
    <a href="#" id="add_subtask">Add subtasks</a>
</p>
<div id="subtask_container"></div>

You can simply wrap your subtask append in a div and simply use .parent() and .remove() function on that. No need to use <br>

Also, do not use .fa-times as primary click event handler as you might have other fa-times on the same page as well Which might cause issues later on. Add a custom class to your fa item (.subtask_remove_icon)

Live Demo:

var i = 1
$("#add_subtask").click(function() {
  $("#subtask_container").append('<div><input name="subtask' + i + '" class="mt-1" id="subtask' + i + '" placeholder="Enter subtask"><i class="fas fa-times ml-1 text-muted subtask_remove_icon"></i></div>');
  i++;
});

$(document).on('click', '.subtask_remove_icon', function() {
  $(this).parent().remove(); //remove the input when X clicked
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://kit.fontawesome.com/a076d05399.js"></script>

<p class="text-muted">
  <i class="fas fa-tasks mr-2"></i>
  <a href="#" id="add_subtask">Add subtasks</a>
</p>
<div id="subtask_container"></div>

Related