HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Checking to see if value is in datalist or not

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
checkingdatalistvalueseenot

Problem

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?

Solution

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

Code Snippets

array.indexOf(element)
array.some(callback)

Context

StackExchange Code Review Q#90125, answer score: 3

Revisions (0)

No revisions yet.