0

I need to change the text of the button after the success adding to the basket. But it change it just after the second click. How can I change it if Im using foreach in php

<td>
<?if(count($arElement["OFFERS"]) > 0):?>
    <?foreach ($arElement["OFFERS"] as $offer): ?>
        <?//var_dump($offer["ID"]);?>
        <div class="button456" >
            <button class="button-offer" id="but123" onclick="add2basket(<?=$offer["ID"]?>)">To the basket</button>
    <?endforeach?>

<?else:>
    <button class="button-simple" id="but1234" data-id="12345" onclick="add2basket(<?=$arElement["ID"]?>)">To the basket</button>
<?endif?>
        </div>
</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 (html) {
            $('button').on('click', function(){
                $(this).closest('button').text("In the basket");
            });
        },
    });
}
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Rinna
  • 11
  • 2
    Good code indentation would help us read the code and more importantly it will help **you debug your code** [Take a quick look at a coding standard](https://www.php-fig.org/psr/psr-12/) for your own benefit. You may be asked to amend this code in a few weeks/months and you will thank me in the end. – RiggsFolly Apr 11 '22 at 07:15
  • 1
    fyi, you could have multiple duplicate `id` attributes, which is invalid, `id`s need to be unique – brombeer Apr 11 '22 at 07:21
  • 1
    This code generates this error `parse error: syntax error, unexpected end of file, expecting "elseif" or "else" or "endif"` Probably among others. Do you have Error reporting turned on – RiggsFolly Apr 11 '22 at 07:22
  • 1
    Another fyi: move the `` inside the `foreach` – brombeer Apr 11 '22 at 07:22
  • @brombeer I try to do unique id like that:$(document).ready(function(){ $('button#but=$arElement["ID"]?>').closest('button').text("In the basket"); }) but ut still not work. How can I do unique id? – Rinna Apr 11 '22 at 07:46
  • Did you also change all of your ` – brombeer Apr 11 '22 at 07:50
  • @brombeer yes i change //var_dump($offer["ID"]);?>
    $('button#but=$offer["ID"]?>').on('click', function(){ $(this).closest('.button456').text("In the basket"); });
    – Rinna Apr 11 '22 at 08:06
  • @RiggsFolly hi, no i dont have this errors – Rinna Apr 11 '22 at 08:22
  • DOnt get the error OR **not looking for or showing the error** – RiggsFolly Apr 11 '22 at 08:23
  • To fix your "second click only" problem remove the second click function `$('button').on('click', function(){ ... }` so it's only `$(this).closest('button').text("In the basket");` - you already clicked the button, no need to add another event listener there – brombeer Apr 11 '22 at 08:26
  • @brombeer I try it, but it dont change the text of the button – Rinna Apr 11 '22 at 11:10

0 Answers0