iAmRoot iAmRoot - 3 months ago 14
jQuery Question

This Object In javascript is not Working

i tried but i cant seem to delete the list when the cross button is clicked. Can Anybody explain why 'this' is not working here ?
Or there is some other way to know which cross button was clicked other than using 'this' object ?



$(function(){
$("#btn").on("click",function(){
var text = $("#input").val();
if(text==""){
alert("please enter a task!");
}
else{
var task = $("<li></li>").text(text);
$(task).append("<button class= 'rem'>X</button>");
$("#ordered").append(task);
}
});
$(".rem").on("click",function(){
$(this).hide(1000);
});

});

<!DOCTYPE html>
<html lang = "en">
<head>
<title>Javascript Addition</title>
<meta charset = "utf-8">

</head>
<body>
<h1>My To-Do List </h1>
<input id = "input" placeholder ="Add your task Here...">
<button id = "btn">clickkk</button>
<ol id = "ordered">
</ol>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script src="todo.js"></script>
</body>
</html>




Answer Source

You can try this

    <!DOCTYPE html>
    <html lang = "en">
        <head>
            <title>Javascript Addition</title>
            <meta charset = "utf-8">
        </head>
        <body>
            <h1>My To-Do List </h1>
            <input id = "input" placeholder ="Add your task Here...">
            <button id = "btn">clickkk</button>
            <ol id = "ordered"></ol>

      </body>
      <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
      <script src="todo.js"></script>
      <script type="text/javascript">
        $("#btn").on("click", function() {
            var text = $("#input").val();
            if (text == "") {
                alert("please enter a task!");
            } else {
                $("#input").val("");
                var task = $("<li></li>").text(text);
                $(task).append("<button class='rem'>X</button>");
                $("#ordered").append(task);
            }
        });

        $("body").delegate( '.rem', "click", function() {
            $(this).parent().hide();
        });
      </script>
    </html>