boruchsiper
boruchsiper

Reputation: 2028

Jquery check two inputs for same value

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

});

Upvotes: 8

Views: 43580

Answers (3)

Gajahlemu
Gajahlemu

Reputation: 1263

Maybe you have miss type your code, try to replace from $(#id1) to $('#id1') so as from $(#id2) to $('#id2')

Corrected code

$('#form').submit(function() {
    var id1 = $('#id1').text(); //if #id1 is input element change from .text() to .val() 
    var id2 = $('#id2').text(); //if #id2 is input element change from .text() to .val()
    if (id1 == id2) {
        alert('Error, cant do that');
        return false;
    }
    else
    {
        return true;
    }
});

Upvotes: 3

Scott
Scott

Reputation: 21882

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.

Upvotes: 8

alex
alex

Reputation: 490153

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

Upvotes: 6

Related Questions