April 28, 2010

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


'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

1 Response to "Using jQuery to Trigger a Link only if a Condition is met"
  1. jetm said...
    April 30, 2010 10:45 AM

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

 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions