views:

1658

answers:

3

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>
A: 

Is this in the function that creates edit buttons?

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

If it this, then it will add this handler multiple times to the same elements, causing a flurry of alerts. Use live, which will place the handler on every matched element, even if is is added later in execution.

geowa4
A: 

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.

xandy
A: 

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;
});
Phairoh
Thanks! This seemed to do it. Live() didn't work neither did preventDefault(), but now it works like charm. Thank you very much.
Oscar Godson