I've been trying to write Jquery code to check if two inputs have the same value on form submit without luck.
If input with id "id1" has the same value as input with id "id2" alert "some text" and return false.
Any help would be much appreciated.
$('#form').submit(function() {
var id1 = $(#id1).text();
var id2 = $(#id2).text();
if (id1 == id2) {
alert('Error, cant do that');
return false;
}
else
{
return true;
}
});
Approach 2: The == operator is used to compare two JavaScript elements. If both elements are equal then it returns True otherwise returns False.
jQuery val() Method The val() method returns or sets the value attribute of the selected elements. When used to return value: This method returns the value of the value attribute of the FIRST matched element. When used to set value: This method sets the value of the value attribute for ALL matched elements.
val() returns an array containing the value of each selected option. As of jQuery 3.0, if no options are selected, it returns an empty array; prior to jQuery 3.0, it returns null . };
DEMO HERE
<input type="text" id="id1" />
<input type="text" id="id2" />
$('input').blur(function() {
if ($('#id1').attr('value') == $('#id2').attr('value')) {
alert('Same Value');
return false;
} else { return true; }
});
I simply used blur rather than a form submit.
It's pretty simple, just do a comparison with ==
and the input's values. Place this inside of the submit()
of your form.
var match = $('#id1').val() == $('#id2').val();
If match
is false
, then you can show your alert()
and event.preventDefault()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With