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>
  <optgroup label="group2">
  <option value=4>item4</option>
  <option value=5>item5</option>
  <option value=6>item6</option>
  </optgroup>
  </select>

  <input type="button" value="Submit" onclick="getOption(this.form)">
<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.

<script>

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);

}

</script>

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:
• Java Script Code for Directory File List
• Easy Picture Zoom Code
• JavaScript Code for Binary to Hexadecimal - Hexadecimal to Binary Conversion
• Code for Java Script Cylinder / Cone Volume Calculator
• Easy Graph Generating Code
• How Far Did the User Scroll?
• Put Commas in Your Java Script Calculators
• JavaScript to Set Checkbox to Readonly
• Easy Slide Show Code With Linked Slides
• Calculators for Your Website : Fahrenheit to Celsius Converter

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