Tutorial :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!


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


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

Its work for me

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »