简体   繁体   中英

Pass Clicked submit button value with Ajax

I am working in wordpress and I have an html form with two submit buttons with same classname and different value. I am passing the submit button clicked value through ajax and show it on the screen. Now my problem is that only first submit button value goes through and second submit button value never gets to show on the screen. Kindly guide and below is my code.

Code

<form id="mydispimage" action="" method="post">
    <select id="category" style="width: 250px; background-color: lightgrey;" name="category">
        <option disabled="disabled" selected="selected" value="">Select category</option>
        <option value="Cutie Pie">Cutie Pie</option>
        <option value="Chubby">Chubby</option>
        <option value="Dimples">Dimples</option>
    </select>
    <input class="displayimage" name="displayimage" type="submit" value="star1" />
    <input class="displayimage" name="displayimage" type="submit" value="star2" />
</form>

JQuery

jQuery(function ($) {
    $(".displayimage").click(function (e) { //form is intercepted
        e.preventDefault();
        //show timer
        jQuery("#timer").css("display", "block");
        jQuery("#participate").css("display", "block");
        var vote = jQuery(".displayimage").val();
        alert(vote);

        //$("#timer").show(slow);
        //serialize the form which contains secretcode
        // var sentdata = $(this).serializeArray();
        //var vote = 1;
        //Add the additional param to the data        
        var sentdata = ({

            action: 'displaymyimage',
            foo: vote
        })

        //set sentdata as the data to be sent
        $.post(yes.ajaxurl, sentdata, function (res) { //start of funciton
            //$("#myresult").append(res.l);
            //alert(res);
            $("#myresult").html(res);
            //$.parseJSON(data);
            return false;
        } //end of function
        ,
        'json'); //set the dataType as json, so you will get the parsed data in the callback
    });  // submit end here

});

Change this

 var vote= jQuery(".displayimage").val();

to this

 var vote= jQuery(this).val();

You need to use $(this) . Otherwise, you will always bring the first value among the elements with matching .displayimage class. That is why you see always the value of the first button.

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