0

I am trying to make a function which checks if the number given is in a specific array. But when I enter a number which is in the array it still alerts bestaat niet but it should alert bestaat

Does someone know why it alerts the wrong message?

Here is my array:

var baas = [
    2951,
    2952,
    2953,
    2954,
    2957,
    2961,
    2969,
    2981,
    2984,
    2985,
    2986,
    2988,
    2989,
    3341,
    3342,
    3343,
    3344,
    3351,
    3352,
    3353,
    3354,
    3355,
    3356,
    3361,
    3362,
    3363,
    3364,
    3366,
    3371,
    3372,
    3373,
    4201,
    4202,
    4203,
    4204,
    4205,
    4209,
    4251,
    4254,
    4255,
    4271,
    4273,
    4284,
    4285,
    4286,
    4287,
    4288,
];

Here is the function:

$('#postalSearch').click(function(){
    var postalInput = $("#postalInput").val();
    var postalInputSuffix = postalInput.match(/\d+/);
    if( $.inArray(postalInputSuffix, baas) !== -1 ) {
        alert('bestaat');
    } else {
        alert('bestaat niet');
    }
});

When I fill in 4288 and alert var postalInputSuffix it does output 4288 but I still get the message bestaat niet.

Thanks for your time!

Jari Rengeling
  • 326
  • 1
  • 15
  • 1
    The array is an integer array. So you have to `parseInt` your value before searching it. – theWellHopeErr Nov 25 '20 at 13:58
  • 1
    In your code `postalInputSuffix ` is a string, but your array consists of `number`s. As such the comparison fails. You'll probably want `$.inArray(parseInt(postalInputSuffix, 10), baas)`. But note: http://youmightnotneedjquery.com/#index_of – Yoshi Nov 25 '20 at 13:58
  • to convert your string in integer just add + before postalInputSuffix : `if( $.inArray(+postalInputSuffix, baas) !== -1 ) {` , just one update to do – Jérôme Teisseire Nov 25 '20 at 14:09
  • You may do 'postalInput.match(/\d+/);' without js if you use input type "number". Jérôme is right, you may use '+' to convert string to number but plus sign is also used for string concatenation. So to be on the safe side it's better to divide your string number by one `if( $.inArray(postalInputSuffix/1, baas) !== -1 )` . – Maxim Dyuzhinov Nov 25 '20 at 21:06

0 Answers0