Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery - infinite loop

Tags:

jquery

I have a webpage which has a button placed inside a div. What i want to achieve is when users click on the div, it would trigger the button inside clicked. The code is something like:

<div id='main'>     
 <input id="button" type="button" onclick="javascript:dosomething();"  value="submit" />
</div>


<script type="text/javascript">
    $(function(){
     $('#main').bind('click', function(){
      $('#button').trigger('click');
     })
    })
</script>

When executed (click on the div), it would throw javascript error "too much recursion". It kinda makes sense why its infinite loop there but I'm not sure what is the right way to achieve this action? (plz dont ask me why i want it that way, its not my code!)

thanks for your kindy help!

like image 344
BeCool Avatar asked Jun 22 '10 04:06

BeCool


1 Answers

Stop event bubbling inside the button click event handler.

Use e.stopPropagation()

If you are using jquery then make all event handlers in jquery way. So the button click will be

$('#button').click(function(e){
    doSomething();
    e.stopPropagation();
});

So the whole thing will be

$(function(){ 
    $('#main').bind('click', function(){ 
        $('#button').trigger('click'); 
    });

    $('#button').click(function(e){
        doSomething();
        e.stopPropagation();
    });

});
like image 193
rahul Avatar answered Oct 05 '22 23:10

rahul