简体   繁体   中英

Preventdefault() function on an anchor working randomly

I have a e-commerce site I'm working on with sessions, I need to prevent default on a href att on a "a" tag when one of the 2 sessions is empty. I managed to do it but it will only fail the first time I add ONLY 1 element to the session in question. To clarify, if I add ONLY 1 element to my "cart" it will still preventdefault, but if I add 2 or more, or remove them in any way or numbers it will work properly preventing only if the cart is empty.

As my site refresh the page to submit the data to my cart session I created a variable called data that will be "1" if the session isn't empty and "2" if session is empty, then I echo the variable on a hidden input with id data and use jquery to check the value of the element data and prevent default when it is different than 2.

// here I define the variable data //

<?php 
if(!isset($_SESSION_["shopping_cart"])){
$data = "1";
}else{
$data = "2";
}
?>

//this is my anchor//

  <li><a id="checkout" href="/bubale/checkout.php" 
  onclick="check();">CHECKOUT</a></li>

// here I insert $data into a hidden input //

   <input type="hidden" id="data" value="<?php echo $data; ?>">

// here if my script //

   <script type="text/javascript">


$( "#checkout" ).click(function( event ) {
    if ($('#data').val() != "2") {
   event.preventDefault();
   alert("Seu carrinho de compras esta vacio");
}

    });




</script>

It should work just fine BUT for some reason the first element added to the cart will still prevent default, my guess is that $data is not changing for some reason.

Any help will be appriciated, even if you have a different way to do this I will be glad to get feedback on this...

May be the function is executed before the document is ready. Try to use document.ready function like this:

$( document ).ready(function() {
    $( "#checkout" ).click(function( event ) {
    if ($('#data').val() != "2") {
   event.preventDefault();
   alert("Seu carrinho de compras esta vacio");
}

    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM