Link
Link

Reputation: 403

check if same value exist in an input box

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

Answers (3)

adeneo
adeneo

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

FIDDLE

Filters the inputs based on wether or not another input with the same value exists

Upvotes: 5

Ja͢ck
Ja͢ck

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

Twisty
Twisty

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

Related Questions