3
\$\begingroup\$

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?

\$\endgroup\$
  • \$\begingroup\$ var arraylist seems useless... you not use it. \$\endgroup\$ – Frogmouth May 11 '15 at 15:31
3
\$\begingroup\$

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.