Quantcast
Channel: Altschuler
Viewing all articles
Browse latest Browse all 60

How to Validate Whether One Input Field Has a Greater Value Than Another Using jQuery

$
0
0

The following code is a complete HTML page that contains a simple form. The jQuery code will display a validation error message when one field of the form contains a greater value than another.

<html>
<head>
	<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
	<script>
		$(document).ready(function() {
			var field1 = $('#field1');
  			var field2 = $('#field2');

			$('.my-form').submit(function(e) {
				var errortxt = 'Field #1 must be greater than field #2';

				if (field1.val() < field2.val()) {
					$('.error-message').text(errortxt);
				}
				e.preventDefault();
			});
		});
	</script>
</head>
<body>
	<form class="my-form">
		<p><input type="text" id="field1"> Enter a value for field #1</p>
		<p><input type="text" id="field2"> Enter a value for field #2</p>
		<p><input type="submit" value="Submit"></p>
		<p class="error-message"></p>
	</form>
</body>
</html>

 


Viewing all articles
Browse latest Browse all 60

Trending Articles