jQuery: how to get which button was clicked upon form submission?

后端 未结 26 1622
旧巷少年郎
旧巷少年郎 2020-11-22 16:01

I have a .submit() event set up for form submission. I also have multiple forms on the page, but just one here for this example. I\'d like to know which submi

26条回答
  •  -上瘾入骨i
    2020-11-22 16:55

    I also made a solution, and it works quite well:
    It uses jQuery and CSS


    First, I made a quick CSS class, this can be embedded or in a seperate file.

    
    


    Next, On the click event of a button within the form,add the CSS class to the button. If the button already has the CSS class, remove it. (We don't want two CSS classes [Just in case]).

        // Adds a CSS Class to the Button That Has Been Clicked.
        $("form :input[type='submit']").click(function () 
        {
            if ($(this).hasClass("Clicked"))
            {
                $(this).removeClass("Clicked");
            }
            $(this).addClass("Clicked");
        });
    


    Now, test the button to see it has the CSS class, if the tested button doesn't have the CSS, then the other button will.

        // On Form Submit
        $("form").submit(function ()
        {
            // Test Which Button Has the Class
            if ($("input[name='name1']").hasClass("Clicked"))
            {
                // Button 'name1' has been clicked.
            }
            else
            {
               // Button 'name2' has been clicked.
            }
        });
    

    Hope this helps! Cheers!

提交回复
热议问题