Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

matching value in array. 1

Status
Not open for further replies.

travisbrown

Technical User
Dec 31, 2001
1,016
Is there a function similar to SQL IN or VB inStr for js?

I need to find out if a selected index value is in in array of numbers.

In pseudo-code...

if (document.form1.txtEmployeeID.value=="" && document.form1.selJobs.options[document.form1.selJobs.selectedIndex].value IN 24,23,44,53,54,54,23,121) {
 
you could write a seperate function that loops through the array and returns a boolean into the if :

function checkArray(matchVal)
{
var match=false;
var myArray= new Array (24,23,44,53,54,54,23,121)
for (i=0;i<myArray.length;i++)
{
if (myArray==matchVal)
{
match=true;
}
}
return match;
}


if (document.form1.txtEmployeeID.value=="" && checkArray(document.form1.selJobs.options[document.form1.selJobs.selectedIndex].value) ) {

Alternatively you could use the JOIN function to convert the array to for example a CSV String and then look for INDEXOF ,<match value>,


Greg Griffiths
Livelink Certified Developer & ECM Global Star Champion 2005
 
You can use the indexOf method. IndexOf will return the starting index in a STRING of the FIRST instance of the string parameter of the indexOf method. If the string is not found it returns -1.

First, parse your array to a string using the .toString() method.

Code:
var numberArrayString = numberArray.toString();


Then add a comma to the beginning and end of your string.
Code:
numberArrayString = "," + numberArrayString + ",";

Now you can compare using the .indexOf() method.

Code:
if (document.form1.txtEmployeeID.value=="" && [!]numberArrayString.indexOf("," + document.form1.selJobs.options[document.form1.selJobs.selectedIndex].value + ",") != -1[/!]) {

Note: I add the commas in case we have numbers like 54 and 540, indexOf could return either case or 40 and 540, but to encapsulate the entire number with commas gets rid of this possible problem.


[small]"I see pretty girls everywhere I look, everywhere I look, everywhere I look. - Band song on movie "The Ringer"[/small]
<.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top