1

I have this array :

    array = ['08','06','05','03','123456'];

when I enter values into a text input I'm checking if there are in the array. This appears to be working.. but I'm finding it's matching on 07 and 123 as well as the values in the array.

$(function() {
 $('#do').on('input', function() {

        array = ['08','06','05','03','123456'];
        do = $(this).val();

        if ($.inArray(do, array) > -1) {
            $(this).css('background-color', '#FFFFFF');
            console.log (do + ' - ' + array + ' - not found');
        } else {
            $(this).css('background-color', '#FAFAFA');
            console.log (do + ' - ' + array + ' - found');
        }
      });
    });

I've created a fiddle, to show this.

All I'm trying to do is change the css background of the input if the value entered in 'do' matches any whole value in the array. If it doesn't match then change the background white.

The array values are coming from php and are formatted as : ['08','06','05','03','123456']

I can change the array layout if needed.

Can any one advise what I'm doing wrong.

Thanks

3
  • 1
    First, you should change the variable do to something else, as do is a JavaScript keyword. Secondly, are there any console errors in the code? Commented Sep 29, 2014 at 16:28
  • Thanks I can change that. No console errors logged at all. Commented Sep 29, 2014 at 16:31
  • Use regex match stackoverflow.com/questions/6298566/regex-match-whole-string Commented Sep 29, 2014 at 18:07

1 Answer 1

3

my first guess was wrong, so i completely changed this answer. $.inArray() evaluates to -1 if the value is not found. otherwise it returns the index of the found value in the array.
so you have got an error in your if condition. just compare using == -1:

$(function () {
    $('#do').on('input', function () {

        var my_array = ['08', '06', '05', '03', '123456'];
        var x = $(this).val();

        if ($.inArray(x, my_array) == -1) {
            $(this).css('background-color', '#f00');
            $("#feedback").text(x + ' - ' + my_array + ' - not found');
        } else {
            $(this).css('background-color', '#0f0');
            $("#feedback").text(x + ' - ' + my_array + ' - found');
        }
    });
});

updated fiddle with more debug-functionality:

http://jsfiddle.net/4qtz5xnr/3/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.