LogicalAnt
LogicalAnt

Reputation: 963

How to check if same input is given using jQuery?

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

Answers (3)

mpm
mpm

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

Mamun
Mamun

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

Sujit Agarwal
Sujit Agarwal

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

Related Questions