简体   繁体   中英

check which button has been clicked in javascript when running a php page via ajax

i have a form on a blog post that displays two submit buttons.

One is save and the other is to delete. Eg:

<form class="updatepost">
<input type="submit" name="saveupdatebutton" class="saveupdatebutton" value="Save">
<input type="submit" name="deleteupdatebutton" class="deleteupdatebutton" value="Delete">
</form>

Currently, i have this for the js:

// JavaScript - Edit Post

$(document).ready(function(){
$(".updatepost").submit(function(){
    var $targetForm = $(this);

    $targetForm.find(".error").remove();
    $targetForm.find(".success").remove();

    // If there is anything wrong with 
    // validation we set the check to false
    var check = true;

    // Get the value of the blog update post
    var $ckEditor = $targetForm.find('.ckeditor'),
        blogpost = $ckEditor.val();


            // Validation
    if (blogpost === '') {
        check = false;
       $(this).css('border', 'solid 1px red');
    } else {
        $(this).css('border', 'none');
    }

      // ... goes after Validation
    if (check) {
    $.ajax({
    type: "POST",
    url: "process/updatepost.php",
    data: $targetForm.serialize(),
    dataType: "json",
    success: function(response){

    if (response.databaseSuccess)
       $targetForm.find('.editor').toggle(),
       <!-- Check for .buildtext id etc to prevent it showing any other posts when updating it -->
       $targetForm.find('#'+response.postid+'').load(''+response.pageurl+' #'+response.postid+''),
       $targetForm.find('#'+response.postid+'').toggle(), 
       $targetForm.find('.edity').toggle(),
       $targetForm.find('.saveupdatebutton').toggle(),
       $targetForm.find('.deleteupdatebutton').toggle();
    else
       $ckEditor.after('<div class="error">Something went wrong!</div>');

}
        });
    }
    return false;
});
});

This obviously runs the code when the form is submitted. But i want to run a different js ajax call depending on what button is clicked.

I have tried this:

// JavaScript - Edit Post

$(document).ready(function(){
$(".saveupdatebutton").click(function(){
     DO STUFF ETC...
});
});

But that doesnt work. Any help how i can determine which button is clicked and then carry out a different js code.

Could try something like:

$(".saveupdatebutton").click(function(){
     $(this).addClass('activeBtn');
});

$(".updatepost").submit(function(){
   var isSave= $(this).find('.saveupdatebutton').is('.activeBtn');

   if( isSave){
       /* save code*/
   }else{
        /* delete code*/
    }

})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM