Welcome to Bucaro TecHelp!

Bucaro TecHelp
Maintain Your Computer and Use it More Effectively
to Design a Web Site and Make Money on the Web

About Bucaro TecHelp About BTH User Agreement User Agreement Privacy Policy Privacy Site Map Site Map Contact Bucaro TecHelp Contact RSS News Feeds News Feeds

Java Script to Get Selected Item from Select List Option Group

An <optgroup> element allows you to group related options in a drop-down select list. Shown below is code for an example of a select list using <optgroup> elements.

<form id="myForm">
  <select id="mySelect" >
  <optgroup label="group1">
  <option value=1>item1</option>
  <option value=2>item2</option>
  <option value=3>item3</option>
  <optgroup label="group2">
  <option value=4>item4</option>
  <option value=5>item5</option>
  <option value=6>item6</option>

  <input type="button" value="Submit" onclick="getOption(this.form)">

since you may have identically named items in multiple optgroups, you need to a way to get the name of the optgroup as well as the name of the option. The code to get this information from the example select list is shown below.


function getOption(form)
var selIndex = form.mySelect.selectedIndex;

var G = form.mySelect.options[parseInt(selIndex)].parentNode.label;

var selText = form.mySelect.options[parseInt(selIndex)].text;

alert(G + " " + selText);



The onclick event of the form's button calls the getOption function, passing it the form as a parameter. The first line in the code extracts the index of the selected option from the select list. The second line of the code uses that index to get the label of the parent node of the selected item, which would be the optgroup element's text. The third line of code uses the index to get the text of the selected option.

You should be able to use this example to design your own select list with optgroups and write the code to get the name of the optgroup as well as the name of the option.

More Java Script Code:
• Create Your Own Database Using Only Notepad : CDV
• Calculators For Your Web Site
• Easy Fading Text Banner Code
• Calculators for Your Website : Decimal to Hexidecimal Converter
• JavaScript Code to Make Image Wave Like a Flag
• Calculate The Points of an Equilateral Triangle
• Java Script Code for Directory File List
• Creating Java Script Dynamic or anonymous Functions at Runtime
• Easy Java Script Animation
• Using a Select List for Navigation

RSS Feed RSS Feed

Follow Stephen Bucaro Follow @Stephen Bucaro

Fire HD
[Site User Agreement] [Privacy Policy] [Site map] [Search This Site] [Contact Form]
Copyright©2001-2018 Bucaro TecHelp 13771 N Fountain Hills Blvd Suite 114-248 Fountain Hills, AZ 85268