If you want to prevent default behavior of any element using jQuery then below little piece of code will help you. For example, the default behavior of the button is click but if you want to prevent it for any reason, then you can use jQuery provide "preventDefault" method.
$(document).ready(function(){ $("#btnSubmit").click(function(e){ e.preventDefault(); }); });Above code will not perform a postback on click of button. ASP.NET developers are familiar with Postback term but still if you are not familiar with Postback term then [A postback is an HTTP POST to the same page that the form is on. In other words, the contents of the form are POSTed back to the same URL as the form.]
When JavaScript was on top, then the developers used to write "return false;" to prevent postback. For example, while submitting the form, you are validating the inputs and if inputs are not valid then you don't want to post the data back to server. So in such scenario, "return false;" is used. Well, you can still use "return false;" with jQuery but a better approach is to use "event.preventDefault()".
But then you might be wondering what is the difference between "return false;" and e.preventDefault(). right? Here is your answer.
The "return false;" statement not only disables the default action but it also stops event bubbling, where e.preventDefault() doesn't stop event bubbling. Read below post for detailed answer and a cool demo.
The difference between ‘return false;’ and ‘e.preventDefault();’
Feel free to contact me for any help related to jQuery, I will gladly help you.
No comments:
Post a Comment