.preventDefault () does not work

1

I am creating an online store as a school project in Laravel. Everything is fine until I want to prevent a button from executing its "submit" action.

{!! Form::open(['url' => '/in_cursos_carts', 'method' => 'POST', 'class' => "addtocart inline-block" ]) !!}
<input type="hidden" name="curso_id" value="{{$curso->id}}">
<input type="submit" value="Agregar al carrito" class="btn btn-info">
{!! Form::close() !!}

That is the code of the Form that I want to "condition with AJAX. And this is the AJAX code that I want to execute so that the submit is executed.

$('.addtocart').on("submit", function(ev)
{   
ev.preventDefault();

var $form = $(this);
var $button = $form.find("[type='submit']");


$.ajax(
{
    url: $form.attr("action"),
    method: $form.attr("method"),
    data: $form.serialize(),


    beforeSend: function()
    {
        $button.val("Cargando...");
    },

    success: function()
    {
        $button.css("background-color", "#00c853").val("Agregado"); 
    },

    error: function()
    {
        console.log(err);
        $button.css("background-color", "d50000").val("Hubo un error.");

        setTimeout(function(){
            restartButton($button);
        }, 5000);
    },
    });

return false;
});


function restartButton($button)
{
    $button.val("Agregar al Carrito").attr("style", "");
};

The idea is that from the view where the products appear the user can add the product to the shopping cart without having to go to the screen where the user will pay but apparently the ev.preventDefault (); It is not running.

    
asked by RalphVB 07.06.2017 в 22:48
source

2 answers

0

If it is a browser version issue this should cover the different alternatives for "preventDefault".

function(ev){
    var  event = ev | window.event;
    if(event.preventDefault){
        event.preventDefault();
    }else{
        event.returnValue = false;
    }

    ...
}
    
answered by 08.06.2017 в 00:19
0

Try adding an id to your button, then add your function inside the jQuery ready event.

$(document).ready(function(){
     $('#botonSubmit').on("click", function(e){
          e.preventDefault();
    });
});
    
answered by 01.07.2017 в 00:08