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
Tweet
No comments:
Post a Comment