How can I compare multiple input field values and if there is a match alert ‘There are similar values’ using jQuery?
<input value="111"> //similar
<input value="222">
<input value="111"> //similar
<input value="333">
This html code above should alert ‘There are similar values’, as it has 2 values which are the same. How can it be done with jQuery?
My tried(Following code doesn’t work):
DEMO: http://jsfiddle.net/HpWLQ/
$('input').each(function () {
var $this = $(this);
var val = $this.val();
vals.push(val);
});
for (var i = 0; i < vals.length; i++) {
for (var n = 0; n < vals.length; n++) {
if (n !== i) {
if (vals[i] === vals[n]) {
alert('There are similar values');
}
}
}
}
Edit: In order to satisfy @Raynos, here’s a pure JS solution.
Bonus: I ran my solutions through jsperf; the last one is obviously by far the fastest.
Edit: Here’s what would probably be the jQuery way of solving your problem (Working fiddle here). My original answer remains below.
Alternative solution in case you need to capture some or all of the duplicate values (Working fiddle here):
As others have mentioned, you were missing a declaration of
valsas an array, therefore,.push()was failing.You might find an object based solution to be more elegant: Working fiddle