2

I have a delete hyper link

<a href="#" class="btn btn-danger btn-mini" id="delCategory">Delete</a>

and my Jquery function

    $(document).ready(function()
    {
        $("#password_validate").validate({
            rules:{
                current_pwd:{
                    required: true,
                    minlength:6,
                    maxlength:20
                },
                new_pwd:{
                    required: true,
                    minlength:6,
                    maxlength:20
                },
                confirm_pwd:{
                    required:true,
                    minlength:6,
                    maxlength:20,
                    equalTo:"#new_pwd"
                }
            },
            errorClass: "help-inline",
            errorElement: "span",
            highlight:function(element, errorClass, validClass) {
                $(element).parents('.control-group').addClass('error');
            },
            unhighlight: function(element, errorClass, validClass) {
                $(element).parents('.control-group').removeClass('error');
                $(element).parents('.control-group').addClass('success');
            }
        });
        $("#delCategory").click(function(){
            alert("Test");
            if(confirm('Are you sure you want to delete this Category?')){
                return true;
            }
            return false;
        });
    });

My other parts of the code can access the #password_validate and make sure the password field is required and all. But the #delCategory from the same HTML page is unable to access the function and return confirmation.

I am able to call the Jquery function from Chrome Console and get the pop-up and confirmation, but my href is failing to call it and it processes the delete without confirming.

  • Where is your _delete_ logic, to begin with? – steven7mwesigwa Mar 14 '21 at 11:00
  • In the Controller. Its Laravel based. public function deleteCategory($id = null) { if(!empty($id)) { Category::where(['id' => $id])->delete(); return redirect()->back()->with('flash_message_success', 'Successfully Deleted Category'); } else { return redirect()->back()->with('flash_message_error', 'Failed to Deleted Category'); } } – Hariharan Thiagarajan Mar 14 '21 at 11:02
  • Well, your `confirm()` demo seems to work just fine. https://jsfiddle.net/theAccountant/Lwrune25/ What specific challenge are you currently experiencing? Did you try putting the _delete_ logic inside the `if...` statement of your `$("#delCategory").click...` event handler? – steven7mwesigwa Mar 14 '21 at 11:13
  • Yes thats the problem. I can call the function from Console in browser by $("#delCategory").click(), but when I physically click the href - it doesn't call the js and directly goes to the controller and performs delete. I have the JS inside a js file and the PHP code inside a controller – Hariharan Thiagarajan Mar 14 '21 at 11:19
  • Are you using a `
    ` to submit the __delete__ request or is it an `$.ajax(...)` call?
    – steven7mwesigwa Mar 14 '21 at 11:20
  • No form No ajax. Just a href click and Jquery to handle the click – Hariharan Thiagarajan Mar 14 '21 at 11:38
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/229888/discussion-between-steven7mwesigwa-and-hariharan-thiagarajan). – steven7mwesigwa Mar 14 '21 at 12:19

1 Answers1

2

Add event.preventDefault() to your click(...) event handler to prevent the default action/behaviour that belongs to the event from occurring. i.e:

Event.preventDefault()

<form  method="POST" action="{{ url('/admin/delete-category/'.$category->id) }}">
    @csrf
    @method("DELETE")
    <input type="hidden" name="id" value="{{$category->id}}">
    <input id="delCategory" type="submit" class="btn btn-danger text-center btn-mini" value="Delete">
</form>

jQuery


$("#delCategory").click(function (e) {

    e.preventDefault();

    if (!confirm('Are you sure you want to delete this Category?')) {
        return;
    }

    const $form = $(this).closest("form");

    $.ajax({
        type: $form.attr("method"),
        url: $form.attr("action"),
        data: {
            "_method": $form.find("input[name=_method]").val(),
            "_token": $form.find("input[name=_token]").val(),
            "id": $form.find("input[name=id]").val()
        }
    });
});

ADDENDUM

If you have multiple "delete" buttons in a single document, you may consider using a class=... attribute instead of id=....i.e:

<!-- Instead of: -->
<input id="delCategory" ...> ❌

<!-- Use this: -->
<input class="delCategory" ...> ✅

Modify the JavaScript accordingly. i.e:

$(".delCategory").click(function (e) {
    // ...

That would ensure that the event handler is applied to all relevant 'dom' elements with a particular class attribute instead of a single dom element matching a unique id attribute.

Resources:
What's the difference between an id and a class?

What is the difference between id and class in CSS, and when should I use them?

steven7mwesigwa
  • 5,701
  • 3
  • 20
  • 34