Joey Estrada
Joey Estrada

Reputation: 404

How can I know the duplicate input element value using jquery?

Im new to web dev and jQuery. I have input element binded with blur event.

This is my code:

// this are my input elements:
<input class="input_name" value="bert" />
<input class="input_name" value="king kong" />
<input class="input_name" value="john" />
<input class="input_name" value="john" />

<script>

    $(".input_name").bind("blur",function(){
          alert(findDuplicate($(this).val()));
    })

    function findDuplicate(value){
          var result = 0;
          $(".input_name").each(function{
                 if($(this).val == value){
                        result++;
                 }
          });
    }

</script>

my main problem is when i change bert to john it returns me 3 result. how would i exempt the event sender from being checked?

Upvotes: 0

Views: 2561

Answers (3)

Anton
Anton

Reputation: 32591

$(".input_name").bind("blur", function () {
    alert(findDuplicate(this.value));
})

function findDuplicate(value) {
    var result = 0;
    $(".input_name").each(function(){
        if (this.value == value) {
            result++;
        }
    });
    return result - 1;
}

DEMO

Upvotes: 1

logic-unit
logic-unit

Reputation: 4313

Try this (untested):

$(".input_name").bind("blur",function(){
    var nth = $(this).index();
    alert(findDuplicate($(this).val(),nth));
})

function findDuplicate(value,nth){
      var result = 0;
      $(".input_name").each(function{
             if($(this).val == value && nth != index){
                    result++;
             }
      });
      return result;
}

Upvotes: 0

Igor
Igor

Reputation: 34021

Like others have mentioned, you've got a few syntax errors. Also, rather than explicitly iterating over all the inputs, you could just have jQuery find them for you using selectors:

$(".input_name").bind("blur",function(){
    alert(findDuplicate($(this).val()));
})

function findDuplicate(value){
    return $(".input_name[value='" + value + "']").length - 1;
}

Upvotes: 2

Related Questions