Button onclick event not working

Hy Guys!

I have a form which is belong to shopping cart.
The button is not submitting data but using an onclick event to add items to the cart. But the onclick event is not working for some reason. When I hit the Add to Cart button it always loads the form action “add_cart.php”. It also doesn’t show any errors when I add more items or not selecting anything. Here is the whole code:

<span id="cart_errors"></span>
<form action="add_cart.php" method="post" id="add_product_form">
  <input type="hidden" name="product_id" value="<?=$id;?>">
  <input type="hidden" name="available" id="available" value="">
  <input type="text" name="quantity" id="quantity">
  <select name="size" id="size">
    <option value=""></option>
    <?php foreach($size_array as $string) {
      $string_array = explode(':', $string);
      $size = $string_array[0];
      $available = $string_array[1];
      echo '<option value="'.$size.'" data-available="'.$available.'">'.$size.' ('.$available.' available)</option>';
    } ?>
<button onclick="add_to_cart();return false;">Add to cart</button>
   val available = jQuery('#size option:selected').data("available");
function add_to_cart(){
  var size = jQuery('#size').val();
  var quantity = jQuery('#quantity').val();
  var available = jQuery('#available').val();
  var error = '';
  var data = jQuery('#add_product_form').serialize();
  if(size == '' || quantity == '' || quantity == 0){
    error += 'Válassz méretet és mennyiséget!';
  else if(quantity > available){
    error += 'Csak '+available' db van raktáron.';
      url: '/tartalomkezelo/admin/parsers/add_cart.php',
      method: 'post',
      data : data,
      success : function(){},
      error : function(){alert("Hiba történt.");}

The default value for the type attribute of button elements is submit. Try changing it to button.

<button type=button>Submit</button>

Okay, thanks! It takes care of the onclick event problem but I don’t get any error messages but I should.

I can’t see anything that looks obviously wrong in the code you posted. If you could make a self-contained example with which I can reproduce the error, I don’t mind taking a closer look.

You mean post the whole product page where the add to cart form is?

Nope. I mean a self-contained example with which I can reproduce the error. Just the form, really.

Meanwhile I figured it out.

val available = jQuery('#size option:selected').data("available");

I don’t believe it, really… :smiley: I typed “val” instead of “var”.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.