Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery check two inputs for same value

Tags:

jquery

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;
    }

});
like image 603
boruchsiper Avatar asked Jan 01 '12 09:01

boruchsiper


People also ask

How can I check if two values are equal in jQuery?

Approach 2: The == operator is used to compare two JavaScript elements. If both elements are equal then it returns True otherwise returns False.

What is val() in jQuery?

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.

What does jQuery val return?

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 . };


2 Answers

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.

like image 100
Scott Avatar answered Nov 15 '22 16:11

Scott


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().

like image 37
alex Avatar answered Nov 15 '22 15:11

alex