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

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.