GTS Joe
GTS Joe

Reputation: 4142

Trigger jQuery AJAX on Specific Button Click

Guys I have the following simple form:

<form action="?edit-form" method="post" enctype="multipart/form-data" class="edit">
    <img src="test.jpg" alt="">
    <input type="submit" name="delete-image" value="Delete Image"><br>
    <input type="submit" name="Go" value="Go">
</form>

And this jQuery:

$(document).on('submit', '.edit', function(e) {
    $.ajax({
        url: $(this).attr('action'),
        type: $(this).attr('method'),
        data: $(this).serialize(),
        success: function(html) { }
    });
    $("img").attr("src", "deleted.jpg");
    e.preventDefault();
});

The jQuery works great, except that I would like it to work only when the "delete-image" button is pressed, not when "Go" is pressed. How do I do this? Right now, the AJAX triggers on submit, I would like it to trigger when "delete-image" is clicked.

Upvotes: 3

Views: 4639

Answers (2)

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Try to get out from the event handler when the event.target mismatches your requirement,

$(document).on('submit', '.edit', function(e) {
  if($(e.target).is('input[type=submit][name=Go]')) { return false; }
  //rest of your code

Upvotes: 2

JanR
JanR

Reputation: 6132

Change your delete image button to a type="button" instead of type="submit" and give it a class or id:

<input type="button" name="delete-image" class="deleteImage" value="Delete Image">

The next step is to capture the click event like this:

 $(document).on('click', '.deleteImage', function(e) {
        //you want to start with blocking the default behavior:
        e.preventDefault();         

        $("img").attr("src", "deleted.jpg");
}

I don't think you need the ajax request here, as you are just manipulating the DOM, however this could be different depending on your actual requirements.

Upvotes: 4

Related Questions