JQuery checks two inputs for one value

I am trying to write jQuery code to check if two inputs have the same value in the submit form with no luck.

If input with id1 has the same meaning as input with id2, "some text" returns false.

Any help would be greatly 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; } }); 
+4
source share
3 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 just used blur, not shape.

+8
source

It's quite simple, just compare with == and input values. Put this inside the submit() your form.

 var match = $('#id1').val() == $('#id2').val(); 

If match is false , you can show your alert() and event.preventDefault() .

+4
source

Perhaps you have missed code, try replacing $(#id1) with $('#id1') so that from $(#id2) to $('#id2')

Fixed 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
source

Source: https://habr.com/ru/post/1388790/


All Articles