Reputation: 963
I've around 100 input fields with class name questionOrder
. I have to check if user given any duplicate entry on the form input.
Currently trying something similar like this:
$('.questionOrder').on('input', function(){
var inp = this.value;
$('.questionOrder').each(function(){
if(inp==this.value){
console.log('match');
}else{
console.log('not match');
}
})
})
Problem here when inputting on a field it also checking it with itself
Upvotes: 0
Views: 85
Reputation: 20155
Alternative answer in pure DOM with event delegation ( without jQuery)
document.body.addEventListener('input', function(event) {
var target = event.target;
switch (true) {
case target.matches('.questionOrder'):
var questions = Array.from(document.querySelectorAll('.questionOrder'))
.forEach(function(q) {
if (q != target) {
if (target.value == q.value) console.log('match');
else console.log('not match');
}
})
return false;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="questionOrder" value="first" />
<input type="text" class="questionOrder" value="second" />
<input type="text" class="questionOrder" value="third" />
<input type="text" class="questionOrder" />
Upvotes: 0
Reputation: 68933
Try to remove this
element from the selector with not()
like:
$('.questionOrder').not(this).each(function(){
Working Code Example:
$('.questionOrder').on('input', function(){
var inp = this.value;
$('.questionOrder').not(this).each(function(){
if(inp==this.value){
console.log('match');
}else{
console.log('not match');
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="questionOrder" value="first"/>
<input type="text" class="questionOrder" value="second"/>
<input type="text" class="questionOrder" value="third"/>
<input type="text" class="questionOrder"/>
Upvotes: 3
Reputation: 12508
You can try siblings function -
$('.questionOrder').on('input', function(){
var inp = this.value;
$(this).siblings().each(function(){
if(inp==this.value){
console.log('match');
}else{
console.log('not match');
}
})
})
Upvotes: 1