JQuery - infinite loop

I have a webpage with a button located inside a div. What I want to achieve is when users click on a div, it causes a button click inside. The code looks something like this:

<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), this will result in a javascript "too much recursion" error. It makes sense, why its an infinite loop, but I'm not sure if this is the right way to achieve this action? (Plz don't ask me why i want it this is not my code!)

Thanks for your kind help!

+5
source share
2 answers

Stop event bubbling events inside the button click event handler.

Use e.stopPropagation()

jquery, jquery. ,

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

,

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

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

});
+7
$("#main").on('click', function (e) {
    e.stopPropagation();
    $("#button")[0].click();
});

0

All Articles