Welcome to Bucaro TecHelp!

Bucaro TecHelp
HTTPS Encryption not required because no account numbers or
personal information is ever requested or accepted by this site

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:
• Easy Java Script Code for Sideways Slide show
• Code to Fade Between Two different Pictures
• JavaScript Code to Make Image Wave Like a Flag
• Easy Picture Zoom Code
• Regular Expressions Intervals
• Easy Moving Popup Code
• Java Script Trim Function
• Java Script Code to Re-arrange Items in a Select List
• JavaScript to Generate a Random Number Between X and Y
• Easy Code to Sort a Table by Column

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-2021 Bucaro TecHelp 13771 N Fountain Hills Blvd Suite 114-248 Fountain Hills, AZ 85268