Answer the question
In order to leave comments, you need to log in
How to change the text of the button after sending the goods to the cart?
After successfully sending the goods to the basket, I need the button text to change to "In the basket", but unfortunately the function only works after the second click on the button, and without the click function it does not work.
The button itself is in a foreach loop.
php code
<td>
<?if(count($arElement["OFFERS"]) > 0):?>
<?foreach ($arElement["OFFERS"] as $offer): ?>
<div class="button456" >
<button id="but<?=$offer["ID"]?>" onclick="add2basket(<?=$offer["ID"]?>)">To the basket</button>
</div>
<?endforeach?>
<?else:?>
<div class="button111">
<button class="but123" id="but<?=$arElement["ID"]?>" onclick="add2basket(<?=$arElement["ID"]?>)">To the basket</button>
</div>
<?endif?>
</td>
<script type="text/javascript">
function add2basket(ID) {
$.ajax({
type: "POST",
url: "/ajax/add_tobasket.php",
dataType: 'html',
data: {
PRODUCT_ID: ID,
QUANTITY: $(".quantity" + ID).val(),
},
success: function (data) {
//так срабатывает только после второго клика
$(document).on('click', 'button', function(){
$(this).closest('button').text("In the basket")
});
$(this).closest('button').text("In the basket");//а так не срабатывает вообще
},
});
}
</script>
Answer the question
In order to leave comments, you need to log in
in success: function(data) you add an event with the first click - when you click on the button, change the text. And on the second click, this event is applied.
I would pass not only the ID to the function, but the entire DOM entity (the button itself).
<button data-id="<?=$offer["ID"]?>" id="but<?=$offer["ID"]?>" onclick="add2basket(this)">To the basket</button>
function add2basket(e) {
var button = $(e);
var ID = button.attr('data-id');
$.ajax({
type: "POST",
url: "/ajax/add_tobasket.php",
dataType: 'html',
data: {
PRODUCT_ID: ID,
QUANTITY: $(".quantity" + ID).val(),
},
success: function (data) {
button.closest('button').text("In the basket");
});
}
You attach a handler to the button when the system has ALREADY tried to add an item to the cart. In the case of "success", you need to look at what comes in "data" and change the content of the button depending on the content. For example, an error occurred and the product was not added to the cart, then you cannot write "in the cart".
If, in principle, do not care about errors, then, regardless of "data", we immediately change the inscription. Those. $(document).on('click'
- not necessary.
How to find which button was pressed? The "ID" of the product comes into the function, using it we find the button on the page and replace the button. Or you can find where the add2basket(ID) function is called and change it there, but this option is worse, because we will not know if there was a response from the server at all.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question