Search code examples
asp.net-mvcjqueryajaxform

How to change specific button value after ajax call


I have a list if items and on each item I have button. When I click on that button I make server call and after that call I need to change button text. So I write this function to ajaxify call:

$('.form').ajaxForm({
            beforeSubmit: function () {                
            },
            success: function (result) {
                $('.itemHoverBox').attr('value', 'Confirmed');
            },
            error: function (xhr, textStatus, errorThrown) {           
            }
        });

This is action button:

@using (Html.BeginForm("Confirm", "Products", new { productId = @t.ProductId }, FormMethod.Post, new { @class="form"}))
{
<input style="width: 60px;" class="itemHoverBox button white" type="submit" value="Confirm" />
}

But this change all itemHoverBox on the page, and what I am trying is just to change button that I clicked. Like when you click favorite question star here on stackoverflow.
My action method returns void for now:

[HttpPost]
        public void CollectTicket(int ticketId)
        {
            ...           
        }

Solution

  • You could capture the form in a closure:

    $('.form').each(function() {
        var form = $(this);
        form.ajaxForm({
            success: function (result) {
                form.find('.itemHoverBox').attr('value', 'Confirmed');
            }
        });
    });
    

    or even cleaner, using the context parameter:

    $('.form').each(function() {
        var form = $(this);
        form.ajaxForm({
            context: form,
            success: function (result) {
                // Here this will equal to the context object we specified
                this.find('.itemHoverBox').attr('value', 'Confirmed');
            }
        });
    });