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

    • This is Reneta's version of Elizabeth Hartman's Fancy Forest quilt. This quilt is a bit of a labour of love. It has A LOT of pieces!...

    • Flying Bird Quilt Blanket The fleece blanket features a lightweight, pill-free microfiber fleece that is not only supremely soft, but warm and cozy.

    • french braid quilt pattern | Thread: My First French Braid Quilt!

    • Follow Me on Pinterest