0

I have a "todo" application that I've added a delete button to. The application is already set up to post via an ajax request, but the delete button causes a page re-load after it is clicked. I feel like preventDefault should... well prevent that from happening, but it doesn't. Any advice would be much appreciated!

function to list tasks

function taskHtml(task) {
        var checkedStatus = task.done ? "checked" : "";
        var liClass = task.done ? "completed" : "";

        var liElement = '<li id="listItem-' + task.id + '" class="' + liClass + '">' +
        '<div class="view"><input class="toggle" type="checkbox"' + " data-id='" +
        task.id + "'" + checkedStatus + ' /><label>' + task.title + 
        '</label><a class="destroy" rel="nofollow" data-method="delete" href="/tasks/' + task.id + 
        '"></a></div></li>';

        return liElement;   

    }

delete task function

function deleteTask(e) {
        e.preventDefault();

        var itemId = $(e.target).data("id");

        $.ajax("/tasks/" + itemId, {
            _method: "DELETE",
        }).success(function(data) {
            var liHtml = taskHtml(data);
            var $li = $("#listItem-" + data.id);
            $li.replaceWith('');
        });
    }


    $.get("/tasks").success( function( data ) {
        var htmlString = "";
        $.each(data, function(index, task) {
            htmlString += taskHtml(task);
        });

        var ulTodos = $('.todo-list');
        ulTodos.html(htmlString);

        $('.toggle').change(toggleTask);

        $('.destroy').click(deleteTask);
    });
2
  • 1
    Change $.ajax("/tasks/" + itemId, { to $.post("/tasks/" + itemId, { and see if it works. Also check the console if possible. Commented Oct 18, 2018 at 17:58
  • @TheAlpha No dice, but I appreciate the tip! Commented Oct 18, 2018 at 18:34

1 Answer 1

1

Remove the href from the <a> tag. I will recommend to change this to a <button> since you are not taking the user to any other page.

I also suspect this will not work:

var itemId = $(e.target).data("id");

Try changing it to:

var itemId = $(this).parent().data("id");

Sign up to request clarification or add additional context in comments.

1 Comment

Why would preventDefault() not stop the href from being followed?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.