My collection of things.

jKafer on the Net

September 26th, 2012 at 11:56 am

Find the Index number of an item in a Javascript Array

I recently was creating a quoting form for a company that I was working for and I wanted to streamline as much as possible (i love to combine things or as I say, get more for my money!). When the quote was completed it would return a description of the items ordered and assign a Smart Part Number to the configuration.

  • So I have a list of categories – with options, setup as radio buttons.
  • When a selection is made I want to load that item (description, price, partNo) into the display area.
  • And build and display the Smart Part number.

TASK: The order in which the items are displayed and added to the display area is very important, so I coded the radio buttons with an ID – then I lookup that ID in an array and get the index number (order number) of that item and that is the placement in the smart part number.

Here is the javascript code I used to do that:

<SCRIPT language = "JavaScript">

//define array outside of a function to make it universally available
var arrPNC = [ "00", "A", "B", "C", "D", "E", "F", "G", "H"];
var itemOrder = 0;

//function to do the lookup and return index(order) must pass a letter
function findItem(tComp){
    findVal=tComp.value  //gets the value from the radio button
	//alert(findVal);  //if you want to see what is being searched for
    for(n=0;n<9;n++){
        //alert(arrPNC[n]); // if you want to see what is checked
        if(arrPNC[n]==findVal)
         {//if matches break from loop and get the index
            itemOrder = n;
        }
    }
     if (itemOrder > 0 ){       
       alert(findVal+ " is in position " + itemOrder + " in the array");
     } else {
       alert(findVal + " was not found in the array. Please try again.");
     }
     itemOrder = 0;
}
</script>

Example of the radio button input tag:
<input id="F" onclick="findItem(this);" type="radio" name="B" value="F" />F

Try it select an item below:

C   D   E   F   G   H   I

-

Comments are closed.

  • Pages

  • Latest Pins on Pinterest

    • Follow Me on Pinterest
  • Quilting Projects I Want to Make

    • Leading Edge Quilt Pattern PDF Download - Etsy

    • Homecoming Quilt- My Peppered Cotton version & tester quilts! – Lo & Behold Stitchery

    • Homecoming Quilt- My Peppered Cotton version & tester quilts! – Lo & Behold Stitchery

    • On the Edge is a quick and fun modern quilt pattern with a lot of custom design possibilities! This PDF pattern includes directions for making a twin-size quilt (72 x 96), a throw-size quilt (56 x 64), a baby size (38.5 x 44), and a pillow/mini quilt (18 x 18). See the Instagram hashtag

    • Adelita Quilt Pattern digital Download - Etsy

    • Follow Me on Pinterest