Event fires once more for each click

Asked

Viewed 275 times

0

I was making a store application, in the application, when clicked on the product image, opens a modal indicating the quantity. This modal has a button submit to send the data in the database.

By clicking on submit the first time the event runs smoothly. The problem is that the second time you click happens as if I clicked 2 times, the third as if I clicked 3 times, and so on.

I searched and found a solution: unbind() or .off(), but I didn’t understand why it happened, when an event ends click should end, no?

In short, my doubts are these:

At the end of the event click the function continues to be executed?

If the .unbind() disables all events click or others, the bind serves to activate them? In other words, it does the same as the .trigger()?

I realized there’s a difference between:

$(document).on('click', "#div", function(){....}); and $("#div").click(function(){...});

I just didn’t understand which, but it seems that when using the second option, there will often be some error, so it is always better to use the first option, correct?

EDITED

As requested I will add the code:

<!-- TRIGGER --> 
<button class="botaopreco" onclick="addcart(<? echo $prod['id']; ?>)">
    Adicionar 
    <i class="fa fa-cart-plus" aria-hidden="true"></i>
</button>

Modal

<!--:::::::::: MODAL :::::::: -->
<div class="modal fade" id="myModal<? echo $contador; ?>" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">

            <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                                <h4 class="modal-title" id="myModalLabel">DETALHES</h4>
            </div>

            <div class="modal-body">
            <div class="imagem-modal">
                <img src="imagens/<?echo $prod['caminho_imagem']; ?>">
            </div>


            <div class="modal-info">

                <div class="info-title">
                 DETALHES
                </div>


                <div class="info-info">
                    <? echo $prod['detalhes']; ?>
                </div>

            </div>

            <br><br>

            <div class="modal-info">

                <div class="info-title-two">
                STOCK
                </div>

                <div class="info-info-two">
                <?
                    if($prod['stock'] == "EM STOCK")
                {
                    echo '<span id="stock'.$prod['id'].'">'.$prod['stock'].'</span>';
                    echo '<i style="color:#7CBB00;position:relative;left:50%;" class="fa fa-circle" aria-hidden="true"></i>'; 
                }

if($prod['stock'] == "ESGOTADO")
{
   echo '<span id="stock'.$prod['id'].'">'.$prod['stock'].'</span>';
   echo '<i style="color:#EA4335;position:relative;left:50%;" class="fa fa-circle" aria-hidden="true"></i>'; 
}
if($prod['stock'] == "APENAS POR ENCOMENDA")
{
    echo '<span id="stock'.$prod['id'].'">'.$prod['stock'].'</span>';
    echo '<i style="color:#FBBC05;position:relative;left:50%;" class="fa fa-circle" aria-hidden="true"></i>'; 
}
?>
</div>

    <div class="info-title-two" style="margin-left:5%;">
        PREÇO
    </div>

    <div class="info-info-two">
        <? echo floatval($prod['preco']); ?>€
    </div>


    <br><br>

    <div class="info-title-two">
    MARCA
    </div>

    <div class="info-info-two">
     <?
        echo $prod['marca'];
     ?>
    </div>

    <div class="info-title-two" style="margin-left:5%;">
        DIMENSÕES
    </div>

    <div class="info-info-two">
        <? echo $prod['dimensoes']; ?>
    </div>

    </div>

Jquery

    function addcart(x)
    {
        //FECHAR MODAL
        $("#modal-overlay"+x).click(function(){
            $("#modal-overlay"+x).hide();
            $("#modal-in"+x).hide();
        });

        var stock = $("#stock"+x).text();

        //VERIFICAR SE EXISTE STOCK
        if(stock == "EM STOCK" || stock == "APENAS POR ENCOMENDA")
        {
            $("#modal-in"+x).show();
            $("#modal-overlay"+x).show();

            //ADICIONAR NO CARRINHO
            $("#quant-enter"+x).off().on('click',function() {

                var prod = x;
                var quant = 0;
                var quant = $("#quant-val"+x).val();

                $.post('adicionar_item.php',
                {
                    prod:prod,
                    quant:quant
                },
                function(data)
                {
                    if(data == "404")
                    {
                        location.href = 'login.php';
                    }
                    else
                    {
                        $("#modal-in"+x).hide();
                        $("#modal-overlay"+x).hide();
                        $(".hue").text(data);
                        swal({   
                            title: "Adicionado!",   
                            text: "O produto foi adicionado ao seu carrinho", 
                            timer: 2000,  
                            imageUrl: "imagens/shop.png" 
                        });
                    }
                });
            });

        }
        else
        {
            swal("Erro!","O item escolhido não se encontra em stock","error");
        }
    }

P.S. To create unique id’s I create a static and add the primary key of the database table, then pass by the function.

  • 2

    Without seeing its original code, it is not possible to say what the problem was. But probably every click you were adding one more Einstein without realizing it.

  • 3

    Put the code here.

  • So I think if it’s clicked is falling sum, use statement to reset count. This is difficult without code and I can help =.=

  • 1

    These situations usually happened when I loaded pages that contained Avascripts several times. It is best to use the event .on and avoid using inline html events. In short a difference between jQuery("#div") and jQuery(document).on(..,"#div") is: the first will give the bind elements that already exist on the screen and if any is added dynamically the event (in this element) will not be executed. The second already "encompasses" these dynamically created elements.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.