# Checking to see if value is in datalist or not

I have a form that is used for inputting data, one of the fields is a datalist with around 6000 options in it, I needed to check that the value entered in to the datalist is actually in the list, here is what I came up with,

$('#submit').on('click', function (e) { var datalistval =$('#ItemSelect').val().split('|');
datalistval = $.trim(datalistval[0]); var IsinList;$("#jobs option").each(function ()
var arraylist = $(this).val().split('|'); arraylist =$.trim(arraylist[0]);
if ($(this).val() != datalistval) { console.log($(this).val());
console.log("Not there ");
} else {
console.log("there");
IsinList = true;
return false;
}
});

if (IsinList !== true) {
alert('Please check the product code as it is not in the list, make sure you select an option in the list ');
e.preventDefault();
}
});


Is this the most optimum way of doing this? Is there anything I can do to improve it?

• var arraylist seems useless... you not use it. – Frogmouth May 11 '15 at 15:31

Your code is a bit hard to read, but I suggest that

array.indexOf(element)


or

array.some(callback)


is what you are looking for.

Documentation:

indexOf

some

• some is IE9+ – Frogmouth May 11 '15 at 15:26
• you can always replace some() with for(..) loop with return inside it – Katerina Pavlenko May 11 '15 at 19:35
• That's true! ... However the OP's code seems a little bit strange. – Frogmouth May 12 '15 at 7:29