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();
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With