jQuery input value validation on duplicate same input name

I am trying to validate the input value on duplicate on using the same input name[] to show me an alert.

like if the value already exist in any input it show me an alert, my code showing the alert but some time.

   <input type="text" name="number" placeholder="number" value="123" /><br /><br /><br />
    <form id="myform">
      <input type="text" name="foo[]" value="123" />
      <br />
      <input type="text" name="foo[]" value="456" />
      <br />
      <input type="text" name="foo[]" value="123" />
      <br />
      <input type="text" name="foo[]" value="789" />
      <br />
      <br />
    </form>
    $("input[name='number']").keypress(function(e) {
         if (e.which == 13) {
           if ($.trim($(this).val()) !== "") {
             if ($.trim($(this).val()) == $('input[name="foo[]"]').val()) {
               alert('VALUE : ' + $.trim($(this).val()) + ' is already exist');
               return false;
             }
           }
         }
       })

jsfiddle

I believe you need to loop through the input collection using each as you can’t compare the values otherwise.

https://learn.jquery.com/using-jquery-core/iterating/

1 Like

thank you…
problem solved

       $("input[name='number']").keypress(function(e) {
         if (e.which == 13) {
           if ($.trim($(this).val()) !== "") {
             $($('input[name="foo[]"]')).each(function(index, element) {
               if ($.trim($(this).val()) == $('input[name="number"]').val()) {
                 alert('VALUE : ' + $.trim($(this).val()) + ' is already exist');
                 return false;
               } else { console.log("OK")}
             });
           }
         }
       })

I am getting alert that is ok but still showing console… event I write return false code.
Please help to fix this

:slight_smile: quote=“wawane7256, post:4, topic:411984”]
but still showing console…
[/quote]

You are checking against a value and if it doesn’t match then you console.log('ok). The console is in a loop so each time there’s no match it will output ok. Therefore if you don’t have a match you should see ok in the console 4 times.

If you do have a match then you will get the alert and then you return. However the match may not occur on the first item so you get ok printed each time until the match is made.

Do you see your logic?

If you only want ‘ok’ output when nothing matches then you need to change the logic a little.

I;m sure one of the JS gurus will be around to tidy this up but you could set a boolean value as the check instead.

e.g.

$("input[name='number']").keypress(function (e) {
  if (e.which == 13) {
    if ($.trim($(this).val()) !== "") {
      var exists = false;
      $($('input[name="foo[]"]')).each(function (index, element) {
        if ($.trim($(this).val()) == $('input[name="number"]').val()) {
          exists = true;
          return false;
        }
      });
      if (exists === true) {
        alert("VALUE : " + $.trim($(this).val()) + " is already exist");
      } else {
        console.log("OK");
      }
    }
  }
});

It might be better to get rid of all those nestings and do something like this instead.


$("input[name='number']").keypress(function (e) {
  if (e.which !== 13 || $.trim($(this).val()) === "") {
    return;
  }
  var exists = false;
  $($('input[name="foo[]"]')).each(function (index, element) {
    if ($.trim($(this).val()) == $('input[name="number"]').val()) {
      exists = true;
      return false;
    }
  });
  if (exists === true) {
    alert("VALUE : " + $.trim($(this).val()) + " is already exist");
  } else {
    console.log("OK");
  }
});

As I said above I;m sure the gurus around here will optimise that much better than me.:slight_smile:

Let’s… simplify just… just a little bit. I’m going to stick as closely to the original code as is practicable. This code is probably not optimized.

I’m gonna start from your code.

       $("input[name='number']").keypress(function(e) {
         if (e.which == 13) {
           if ($.trim($(this).val()) !== "") {
             $($('input[name="foo[]"]')).each(function(index, element) {
               if ($.trim($(this).val()) == $('input[name="number"]').val()) {
                 alert('VALUE : ' + $.trim($(this).val()) + ' is already exist');
                 return false;
               } else { console.log("OK")}
             });
           }
         }
       })

Now… i’m gonna get out the crayons for a sec.

           if ($.trim($(this).val()) !== "") {
             $($('input[name="foo[]"]')).each(function(index, element) {
               if ($.trim($(this).val()) == $('input[name="number"]').val()) {
                 alert('VALUE : ' + $.trim($(this).val()) + ' is already exist');

Anytime you’re running the same functions multiple times, especially inside a loop, you’re in trouble. Give the Javascript engine a rest.
Let’s… just…store it once. The value wont be changing while we’re inside this function.

      $("input[name='number']").keypress(function(e) {
         let thisval = $(this).val().trim();

Now, as Paul points out, you’ve got an if inside an if with nothing else around it. So we can combine the conditions…
if(e.which == 13 && thisval !== "") {
(also, see already how much easier it is to read?)

I dont know why we’re double-wrapping the each selector… so lets not.
$('input[name="foo[]"]').each(function(index, element) {

Now, notice there that the each function has already selected our element for us. We dont need to select it again. It’s a standard Javascript HTMLElement at this point, so we access its value normally.
if(thisval == element.value) {

If we hit a match, alert and return.

                 alert('VALUE : ' + thisval + ' already exists');
                 return false;
} //EndIf

If it didnt match… we do nothing. Why?

}); //EndEach

If we get to this point, there was no match anywhere. If we had gotten a match, the return would have stopped the function already. So if we get here, we KNOW there were no matches anywhere in the set. So here we can put our “OK”, without needing a flag variable.

console.log("OK");
} //EndOuterIf
}); //EndFunction

So… put it all together:

$("input[name='number']").keypress(function(e) {
  let thisval = $(this).val().trim();
  if(e.which == 13 && thisval !== "") {
    $('input[name="foo[]"]').each(function(index, element) {
      if(thisval == element.value) {
        alert('VALUE : ' + thisval + ' already exists');
        return false;
      } //EndIf
    }); //EndEach
  console.log("OK");
  } //EndOuterIf
}); //EndFunction
1 Like

My condensed version:

$("input[name='number']").keypress(function(e) {
 if(e.which == 13 && e.target.value !== "" && $('input[name="foo[]"]').filter((x,el) => el.value == e.target.value).length > 0) { console.log("Collision"); }
});
4 Likes