How to use IndexOf in JQuery

Blessing Thinker picture Blessing Thinker · Jul 21, 2013 · Viewed 87.6k times · Source
if($('#this').val().indexOf('4289')){
    Do something
else
    Do something. 

This works only with that 4289,
When I try to add other numbers to be indexed next to it using 'or', it doesn't work. How should I put other number. E.g

IndexOf('4289||78843') 

I want this to check this numbers and if the number in the input field is not one of this, to echo error.

Here's more which happens to die when one revisits the field.

$('#Zip').blur(function(){
        if (($(this).val().indexOf('0860') > -1)||($(this).val().indexOf('0850') > -1)){
        $('#Status_Zip').html("No way.")
        $(this).alterClass('*_*', 'Success')
        return false;
        }else{$('#Status_Code').hide()
        $(this).alterClass('*_*', 'Error')
        $(this).css('border-color', '#F00').css('background-color', '#FFC').effect("pulsate",{times:4},2)
            return true;
        }
    })

Answer

David picture David · Jul 21, 2013

That's because it would be looking for the string '4289||78843', which doesn't exist in the target I'm assuming. Logical operators can't just be tossed in anywhere, only where there are actual values to logically operate on. Something like this:

if(($('#this').val().indexOf('4289') > -1) ||
   ($('#this').val().indexOf('78843') > -1))

The return value of the indexOf() function is the numeric index of that value in the target value, or -1 if it's not found. So for each value that you're looking for, you'd want to check if it's index is > -1 (which means it's found in the string). Take that whole condition and || it with another condition, and that's a logical operation.

Edit: Regarding your comment, if you want to abstract this into something a little cleaner and more generic you might extract it into its own function which iterates over a collection of strings and returns true if any of them are in the target string. Maybe something like this:

function isAnyValueIn(target, values) {
    for (var i = 0; i < values.length; i++) {
        if (target.indexOf(values[i]) > -1) {
            return true;
        }
    }
    return false;
}

There may even be a more elegant way to do that with .forEach() on the array, but this at least demonstrates the idea. Then elsewhere in the code you'd build the array of values and call the function:

var values = ['4289', '78843'];
var target = $('#this').val();
if (isAnyValueIn(target, values)) {
    // At least one value is in the target string
}