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

Holiday Gift Guide
Holiday Gift Guide

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:
• Allowing Multiple Selections from Drop-down Select List
• Java Script Code to Calculate Speed / Distance of Falling Object
• JavaScript Code for Binary to Decimal - Decimal to Binary Conversion
• Java Script Trim Function
• Java Script Code to Factor Numbers
• Java Script Random Password Generator
• Easy Slide Show Code With Linked Slides
• Easy Java Script Butterfly Animation
• Code to Block the Ad Blockers
• Java Script Message Boxes

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