3

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.

2 Answers 2

4

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.

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

1 Comment

Thanks JanR, your code worked great. About the AJAX, I actually do need it since I'm also doing a MySQL query when the delete button is clicked (I'm dropping the image's filename from the db).
2

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

Comments

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.