Steve Voltmer Steve Voltmer - 2 months ago 20
jQuery Question

Return a Boolean from a jQuery map() function

I am passing a jQuerey selector as an argument and a year value into a function to test the value against a array of all the values from my select (the jQuery selector argument). I need it to return a Boolean true if any of the options values are the same as the "value" argument, but it always returns undefined. Is there a way to return a Boolean from a map()?

function checkOptions(selector, prop) {
var options = selector.children('option');
var selectorValues = $.map(options, function(option) {
if( option.value == prop ){
return !!(option.value == prop);
}
});
}


After changing my original code to reflect the suggestions made, the function still returns "undefined".

function checkOptions(selector, prop) {
var result;
var options = selector.children('option');
var selectorValues = $.map(options, function(option) {
return option.value == prop;
});
}


The variable "selectorValues" holds these values at run-time:
selectorValues = [false, false, true, false, false]
This makes sense, because I am passing a "year" to prop that is one of the values of the options of the select.

Answer

The map function is not properly used in this situation which is why you got in trouble. It's role is to apply a transformation for each element of the array. Check out the some function. It is a predefined javascript function which does exactly what you want.

I would take the "array" of jquery objects, turn them into a native javascript array and call the some method on the them checking the desired condition.

function checkOptions(selector, prop) {
  var options = selector.find('option').toArray();
  var result = options.some(function(currentValue) {
    return (currentValue.text == prop); //using type coercion
  });
  return result;
}