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





About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

1 comment:

Unknown said...

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