Help with Javascript & HTML [duplicate]

1

I have a form created based on append() of JavaScript as a result of the obtained in AJAX to receive and manipulate PHP Array converted to JSON. I also have a on to capture the form when it makes submit() , but there's the problem, the form is not captured, and the submit is done normally, the preventDefault() does not work.

jQuery(document).ready(function($) {

    var array_vehiculos = new Array();

    $.ajax({
        type: 'POST',
        url: 'data/load_veh.php',
        cache: false,
        success: function(data){
            array_vehiculos = JSON.parse(data);
            $.each(array_vehiculos,function(index,val){
                $(".content.c-veh").append(
                    '<div class="sub-item">'+
                        '<form method="POST" id="veh">'+
                            '<input type="hidden" name="val-veh" value="'+val['matricula_veh']+'">'+
                            '<button type="submit" class="nothing">'+
                                '<img src="img/taxi/taxi.png" class="imgfit">'+
                            '</button>'+
                        '</form>'+
                    '</div>'
                );
            });
        }
    });
    $("#veh").on('submit', function(event) {
        event.preventDefult();
        alert("Hola");
    });
});

Edit

  • I had an error in writing preventDefault (), I had written preventDefult ().
asked by Máxima Alekz 11.10.2016 в 05:54
source

1 answer

3

As I put in a comment this is a duplicate of other questions already in StackOverflow in Spanish (here I leave 1 , 2 , and 3 examples, they all look completely different, but they all have the same root problem)

The problem is that the event handler submit is being associated with an element before that element is created in the DOM. Events should be associated in a delegated way.

Where do you do this:

$("#veh").on('submit', function(event) {
    event.preventDefault();
    alert("Hola");
});

You should be doing this by using delegation of events :

$("body").on('submit', "#veh", function(event) {
    event.preventDefault();
    alert("Hola");
});

But still you can find another problem. As it is the same time the code, it seems that could be the case of duplicate IDs, which can go a little crazy to jQuery. It would be better if instead of giving everyone the ID veh , you would put it as a class.

    
answered by 11.10.2016 / 06:09
source