Check if the same value exists in the input field

In any case, to check if a similar value exists in the input field

EX:
<input name="user1" value="bla1">
<input name="user2" value="bla2">
<input name="user3" value="bla1">

When submitting the form, verification will be checked, it will warn the user and add a class to the input with the same value.

+4
source share
3 answers

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');

Fiddle

Filters inputs based on a particular input with the same value

+4
source

This is one way using a temporary object to track items of a specific 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">
Run codeHide result
+1
source

- :

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;
    }
  }
});
0

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


All Articles