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