Question

I need a way to prevent multiple submits:

$("#myDiv").click(function(e) {
    e.preventDefault();
    console.log('open');

    // submit the form    
    $('#myDiv #myInput').click(function(e){
        e.preventDefault();
        /* ajax call here */
        console.log('clicked');
    });

});

So if when I click #myDiv is sending X times click to the child function.

eg. if you click 3 times #myDiv and then click #myInput will send 3 times the form, and if you press again will send 6.

Any ideas how to fix it?

Was it helpful?

Solution

Seems like you are binding click event handler multiple times for $('#myDiv #myInput')..

You should either move the $('#myDiv #myInput').click(function(e){ outside the click handler of $("#myDiv").click(function(e) { or use .one(. Note that in both cases the behavior is different.

Also use should use event.stopPropagation(); to stop event bubbling.

Try below code as per your requirement. The below items 1. and 2. works differently, so please understand the code and implement as per your requirement.

  1. Moving #myInput click event outside

    $("#myDiv").click(function(e) {
    e.preventDefault();
    e.stopPropagation();
    console.log('open');
    });
    
    // submit the form    
    $('#myDiv #myInput').click(function(e){
       e.preventDefault();
       e.stopPropagation();
       /* ajax call here */
       console.log('clicked');
     });
    
  2. Please note that the click handler for #myInput will be executed once.

    $("#myDiv").click(function(e) {
       e.preventDefault();
       e.stopPropagation();
       console.log('open');
    
       // submit the form    
       $('#myDiv #myInput').one(function(e){
        e.preventDefault();
        e.stopPropagation();
        /* ajax call here */
        console.log('clicked');
       });
    });
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top