Kiroyasha Kiroyasha - 7 months ago 15
HTML Question

How can I remove the contents I create with my button

On a follow up to another question, I'm new at JQuery here... I have an assignment to create a simple JQuery to choose a date, type an event and add them to a list with a small red button in front of each item.

The code I have is as follows:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Datepicker - Display month &amp; year menus</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

<link rel="stylesheet" href="css.css">

<script>
$(function() {
$( "#datepicker" ).datepicker({
changeMonth: true,
changeYear: true
});
});

$(document).on('click', '#bta', function () {

if ($('#datepicker').val() != '' && $('#evento').val() != '' ) {
$('#caixa').prepend('<p>' + $('#datepicker').val() + '&nbsp;' + $('#evento').val() + '&nbsp;' + '<input type="button" id="apagar" class="apagar" value="apagar"/>' + '</p>');
$('input').val('');
}

});

$(document).on('click', '#apagar', function () {
$( "p" ).remove();
});

</script>
</head>

<body>
<div id="box">
Lista de Tarefas:
<br><br>
Date: <input type="text" id="datepicker"> &nbsp; &nbsp;

Event: <input type="text" id="evento"> <button id="bta" class="bta">+</button>

<div id="caixa"> </div>
</body>
</div>

</html>


The problem I have is pretty simple, the red button I create is supposed to erase the full line I created and that particular line only, the problem is that the red button erases every single content I have on the list.

I know it's because they all have the paragraph tag but how do I do it so that the button erases a single line only?

This is the second question I ask today and I usually don't do this but this is due in like 2-3 days but my next few days are unpredictable when it comes to free time so that's why I'm making a second question today...

Thanks in advance.

Answer

Instead of deleting all "p", you can delete only nearest "p".

Change this line:

   $( "p" ).remove();

With this one:

   $(this).closest("p").remove();

You have here a full example: http://jsbin.com/gikululofu/edit?html,output