5

I have a jquery ajax call that load a form inside a div and I want to prevent submit of this form but if I use jquery submit function with

$("form").submit(function(e){
  e.preventDefault(e);
  alert('submit intercept');
});

It does not work if I place in a external js file but works if I put in a script tag after the form that loaded via ajax call.

Peter B
  • 22,460
  • 5
  • 32
  • 69
danny36
  • 131
  • 2
  • 11
  • 4
    Yes, you can attach event listeners only to existing elements. "Event delegation" is your keyword when searching ... – Teemu Apr 11 '18 at 07:52

2 Answers2

1

You can use $(document) selector and on() method for elements that are dynamically generated:

$(document).on('submit', 'form', function(e) {
    e.preventDefault();
    alert('submit intercept');
});
SilverSurfer
  • 4,281
  • 6
  • 24
  • 50
0

You don't need to use submit.

Instead, You can try this:

$('#submit-button').on('click', function() {
    var userId = $('#user-id').val();
    var content = $('#content').val();
    $.ajax({
        type : 'post', 
        url :'url',
        processData : false,
        cache : false,
        contentType : false,
        data : {
            'userId' : userId,
            'content' : content
        },
        dataType : 'json',
        success:function(result){
            alert('success!');
            var userId = $('#user-id').empty();
            var content = $('#content').empty();
        },
        error:function(e){
            console.log(JSON.stringify(e));
        }
    });
});

However, you don't need 'form' tag anymore. Since if submit it the page changes, if you want to use ajax, which is asynchronous should not change the page.

c-an
  • 3,543
  • 5
  • 35
  • 82
  • I can't modify form because it's a part of a CMS – danny36 Apr 11 '18 at 08:07
  • 1
    You should always hook to the submit event where possible. It's better semantically. You should also always use a `form` element, even when making an AJAX request as it's essential for accessibility reasons. – Rory McCrossan Apr 11 '18 at 08:20