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

Victims of Sandy Hook

Stop the Slaughter of Innocents. Congress is bought and paid for by gun lunatics and gun promotion groups. If you want to live in a safe America, help buy Congress back for America. Send a donation to Mayors Against Illegal Guns, 909 Third Avenue, 15th Floor New York, NY 10022

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.

RSS Feed RSS Feed

Follow Stephen Bucaro Follow @Stephen Bucaro

Web Design Sections

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