Using jQuery to Trigger a Link only if a Condition is met

I was recently asked a question. How to prevent a link from triggering if a condition is not met. Here’s a very simple code to do so. If the values of two textboxes do not match, the link does not get clicked. If the values match, the user is navigated to the URL the link points to.

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Prevent a Link from Navigating</title>
<
script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js">
</
script>
<
script type="text/javascript">
$(function() {
$('#anc').click(function(e) {
if($("#Text1").val() != $("#Text2").val())
e.preventDefault();
});
});
</script>
</
head>
<
body>
<
form id="form1" action="">
<
input id="Text1" type="text" /><br />
<
input id="Text2" type="text" /><br />
<
a id="anc" href="http://www.dotnetcurry.com">Click me</a>
</
form>
</
body>
</
html>

Note: You should add an extra check to see if the boxes are not empty.

Live Demo


Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

1 comment:

jetm said...

Nice Tips for using in Validation.
jQuery Rocks!!!