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')" class="btn btn-default acceptbtn">Accept</a>
Advertisement
Answer
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(...); });