jQuery / JavaScript Bubbling and stopPropagation doesn't work

11,041

Solution 1

An event can have multiple event listeners. Each time you use $(element).submit(whateverFunction) you are adding another whateverFunction to the submit event. If you only want only the last listener to be the action that is taken upon envoking the event, try doing this:

function modal_submit(the_id){

$('#modal form').unbind(); // this will remove all other event listeners from this element

$('#modal form').submit(function(){
        //This will alert every time I have EVER clicked on an edit button
        alert(the_id);
        return false;
});

Solution 2

I think you event.stoppropagation does its job already. It stopped all the bubbling on the click event of the button (ie, if you try checking the document body, it won't have mouse click event anymore). The reason why codes within submit of the form is still executed, is because this is called by the button's default action.

Together with event.stoppropagation(), I suggest you include this:

event.preventDefault();

So that the default action will not used and only the codes within your handler is executed.

Share:
11,041
Oscar Godson
Author by

Oscar Godson

Fork me on Github: http://github.com/oscargodson Read my stuff: http://oscargodson.com

Updated on June 04, 2022

Comments

  • Oscar Godson
    Oscar Godson almost 2 years

    I'm making an edit button which pops up a modal box with a form to edit it. jQuery then sends this form to my server and I get a JSON response back. However, due to my bubbling issue, if I click on, for example, all of the edit buttons and then click on the last one and change a field, it does it across all of them.

    $('.edit').click(function(event){
     //more code...
        modal_submit(the_id);
        event.stopPropagation();
    });
    

    and then the submit event:

    function modal_submit(the_id){
    $('#modal form').submit(function(){
        //This will alert every time I have EVER clicked on an edit button
        alert(the_id);
        return false;
    });
    

    }

    finally all of this is inside of a getScript:

    $.getScript('js/edit.js',function(){
    create_edit_btn();
    

    });

    I've only used this 1 other time, and it worked, but I also had to do this.event.stopPropagation, but if I do "this" now it says this.event is undefined, but like I said, this exact code worked before for another script I did.

    Does anyone have any ideas? :\

    EDIT:

    the html is: 
    <li> 
      <input id="item1" type="checkbox" value="webhosting|15" title="Web Hosting">  
        <p>Hosting for your web site</p>
    </li>
    
  • Oscar Godson
    Oscar Godson almost 15 years
    Thanks! This seemed to do it. Live() didn't work neither did preventDefault(), but now it works like charm. Thank you very much.