jQuery.inArray(), how to use it right?
inArray
returns the index of the element in the array, not a boolean indicating if the item exists in the array. If the element was not found, -1
will be returned.
So, to check if an item is in the array, use:
if(jQuery.inArray("test", myarray) !== -1)
jquery inArray usage
You could check for the keyword with JavaScript indexOf method. This is check for each element of the array:
$("#get").click(function(){
$(".name").each(function(){
var fisier = $(this).text();
if(fisier.indexOf("migr") !=-1){
alert('Keyword found');
}else{
alert('Keyword not found');
}
});
});
Should I use jQuery.inArray()?
Well internally inArray
makes a simple loop, I would recommend you to check if there is a native Array.prototype.indexOf
implementation and use it instead of inArray
if available:
function findPoint(point, list) {
var l = list.map(function anonMapToId(p) { return p.id });
var found = ('indexOf' in Array.prototype) ? l.indexOf(point.id)
: jQuery.inArray(point.id, l);
return found;
}
The Array.prototype.indexOf
method has been introduced in browsers that implement JavaScript 1.6, and it will be part of the ECMAScript 5 standard.
Native implementations are way faster than non native ones.
JS jQuery - check if value is in array
You are comparing a jQuery object (jQuery('input:first')
) to strings (the elements of the array).
Change the code in order to compare the input's value (wich is a string) to the array elements:
if (jQuery.inArray(jQuery("input:first").val(), ar) != -1)
The inArray
method returns -1
if the element wasn't found in the array, so as your bonus answer to how to determine if an element is not in an array, use this :
if(jQuery.inArray(el,arr) == -1){
// the element is not in the array
};
jQuery inArray returning false when needle exists in haystack
Your code seems to be working just as expected.
Note that $.inArray()
will perform a type comparison; I expect you are passing a string. If you are testing for a key that is a string, your isValidCode
function will return false, as your array only contains integer values. You can cast the code to an integer with parseInt
to avoid this issue:
function isValidCode(code){
var arr = [1, 2, 3];
return ($.inArray( parseInt( code, 10 ), arr ) !== -1);
}
Related Topics
Best Way to Call an Asynchronous Function Within Map
How to Wrap/Surround Highlighted Text with an Element
Getting Current Date and Time in JavaScript
How to Trigger the Window Resize Event in JavaScript
I Want to Remove Double Quotes from a String
JavaScript Sleep/Wait Before Continuing
Is JavaScript an Untyped Language
Mobile Safari Autofocus Text Field
Sort by Two Values Prioritizing on One of Them
Calling a JavaScript Function from Managed Bean
How to Replace Remapcolums with Remapcolumnsbyname in Free Jqgrid
How to Create a Dialog with "Ok" and "Cancel" Options
Addition Is Not Working in JavaScript
How to Build/Concatenate Strings in JavaScript
How to Count Certain Elements in Array