Home > database >  Select only the clicked button JQuery
Select only the clicked button JQuery

Time:05-17

I have this ajax function, which should change the style of the clicked button, but for some reason it does not work. I'm not getting any errors in the console and the ajax call is successful Any idea what's wrong here?

function AcceptOffer(id)
{
    var json = {
        id : id
    };

    $.ajax({
        type: 'POST',
        url: "@Url.Action("AcceptOffer", "Product")",
        dataType : "json",
        data: {"json": JSON.stringify(json)},
        success: function() {
            $(this).text("Accepted");
            $(this).css("background-color", "green");
            $(this).css("color", "white");
            $(this).attr('disabled', true);

        },
        error: function(data) {
            alert('Some error');
            window.location.reload();
        }
    });
}
</script> 

Html:

<a href="javascript:void(0)" onclick="AcceptOffer('@item.OfferId')" >Accept</a>

CodePudding user response:

Your issue is with using this incorrectly. The way you are using it, it is going to reference the object you pass into the ajax command

function AcceptOffer(id)
{
    var json = {
        id : id
    };

    var elemYouWantToChange =...;

    $.ajax({
        type: 'POST',
        url: "@Url.Action("AcceptOffer", "Product")",
        dataType : "json",
        data: {"json": JSON.stringify(json)},
        success: function() {
            $(elemYouWantToChange).text("Accepted");
            $(elemYouWantToChange).css("background-color", "green");
            $(elemYouWantToChange).css("color", "white");
            $(elemYouWantToChange).attr('disabled', true);

        },
        error: function(data) {
            alert('Some error');
            window.location.reload();
        }
    });
}

-- Edit --

In javascript, you listen for a click like so:

elem.addEventListener('click', function(e) {
  console.log(e.target); // You need to get e.target to AcceptOffer so it can style the correct element
  AcceptOffer(...);
});

CodePudding user response:

In your code this is not pointing to the anchor tag you just need to pass this reference to your function.

function AcceptOffer(ele, id)
{
var json = {
    id : id
};

$.ajax({
    type: 'POST',
    url: "@Url.Action("AcceptOffer", "Product")",
    dataType : "json",
    data: {"json": JSON.stringify(json)},
    success: function() {
        $(ele).text("Accepted");
        $(ele).css("background-color", "green");
        $(ele).css("color", "white");
        $(ele).attr('disabled', true);

    },
    error: function(data) {
        alert('Some error');
        window.location.reload();
    }
});
}

So the anchor tag will be:

<a href="javascript:void(0)" onclick="AcceptOffer(this, '@item.OfferId')" >Accept</a>
  • Related