Reputation: 403
Is there anyway to check if a similar value exist in an input box
EX:
<input name="user1" value="bla1">
<input name="user2" value="bla2">
<input name="user3" value="bla1">
The verification will trigger when the form is submitted, it will alert the user and add a class to both the input with the similar value.
Upvotes: 5
Views: 5592
Reputation: 318182
More jQuery'ish
var inputs = $('input');
inputs.filter(function(i,el){
return inputs.not(this).filter(function() {
return this.value === el.value;
}).length !== 0;
}).addClass('red');
Filters the inputs based on wether or not another input with the same value exists
Upvotes: 5
Reputation: 173552
This is one way, by using a temporary object to keep track of elements of a particular value:
(function() {
var inputs = {};
$('input').each(function() {
if (inputs[this.value] !== undefined) {
// a previous element with the same value exists
// apply class to both elements
$([this, inputs[this.value]]).addClass('same');
}
inputs[this.value] = this;
});
}());
.same {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="user1" value="bla1">
<input name="user2" value="bla2">
<input name="user3" value="bla1">
<input name="user4" value="bla4">
<input name="user5" value="bla5">
Upvotes: 1
Reputation: 30883
Something like this maybe:
var dup = false;
$.each("input", function(k, v){
if($(this).attr("name") == $(this).next("input").attr("name")){
dup = true;
}
if($this).is(":last")){
if($(this).attr("name") == $("input:first").attr("name")){
dup = true;
}
}
});
Upvotes: 0