8

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

});
3
  • Please post the code you have so far. Though I cannot imagine what can go wrong using the comparison operator. It's so simple that I assume there is something else wrong with your code, or the values. Commented Jan 1, 2012 at 9:10
  • $('#form').submit(function() { var id1 = $(#id1).text(); var id2 = $(#id2).text(); if (id1 == id2) { alert('Error, can't do that'); return false; } else { return true; } }); Commented Jan 1, 2012 at 9:15
  • There are two things wrong with your code: Selectors must be strings, i.e. #id1 must be '#id1', and text() won't retrieve the value of an input field (why do you think it does?), use .val() instead. jQuery's documentation is pretty good and it's the first thing you should read if you are unsure about methods. Simply printing id1 and id2 would have been a good start for debugging. Commented Jan 1, 2012 at 9:17

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

Comments

6

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

Comments

3

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

2 Comments

If #idX are input elements, then .text() won't return their values.
@FelixKling you are right, if #idX are input elements then to retrieve value need to change form .text() to .attr('value') or just .val()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.