BeCool
BeCool

Reputation: 529

Jquery - infinite loop

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!

Upvotes: 5

Views: 5843

Answers (2)

vebs
vebs

Reputation: 345

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

Its work for me

Upvotes: 0

rahul
rahul

Reputation: 187030

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();
    });

});

Upvotes: 7

Related Questions