Link to home
Start Free TrialLog in
Avatar of hankknight
hankknightFlag for Canada

asked on

JavaScript: Count optgroups of select

Using JavaScript, how can I count the number of optgroups of a specific select?

Please do NOT use jQuery for this.

This does NOT work:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Demo</title>
</head>
<body>

<select name="StateProvinceList" id="StateProvinceList">
  <option value="">&nbsp; --- Please Select ---</option>
  <optgroup id="USAStates"  label="USA States">
	<option value="AL">Alabama</option>
	<option value="AK">Alaska</option>
	<option value="AZ">Arizona</option>
  </optgroup>
  <optgroup id="USATerritories" label="USA Territories">
	<option value="AS">American Samoa</option>
	<option value="GU">Guam</option>
  </optgroup>
  <optgroup id="USAForces" label="USA Armed Forces">
	<option value="AA">Armed Forces Americas</option>
	<option value="AP">Armed Forces Pacific</option>
  </optgroup>
  <optgroup id="Canada" label="Province / Territory">
	<option value="AB">Alberta</option>
	<option value="BC">British Columbia</option>
  </optgroup>
</select>

<select name="zzz" id="zzz">
  <option value="">&nbsp; --- Please Select ---</option>
  <optgroup id="x"  label="x">
	<option value="1">1</option>
	<option value="2">2</option>
  </optgroup>
</select>

<script type="text/javascript">

  var StateProvinceList = document.getElementById('StateProvinceList');
  alert('Number of options: ' + StateProvinceList.options.length);
  alert('Number of groups: ' + StateProvinceList.optgroups.length);

</script>

</body>
</html>

Open in new window

SOLUTION
Avatar of Ryan Chong
Ryan Chong
Flag of Singapore image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of hankknight

ASKER

No that does not work.  It does count the optgroups however it also counts top-level select elements so the answer is not correct.  This is dynamic so there could be any number of optgroups and any number of top-level select elements.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial