• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 784
  • Last Modified:

Getting value of selected option in Java Script

I'm trying to get the value of the selected option when a drop down is changed like so;

<select name="months" id="months" onchange="updateMonth();">

However when I change the drop down, the alert says "Undefined"  where it's meant to say "January"

Can someone tell me where I'm going wrong?
function updateMonth() {
	var opIndex = document.book.months.selectedIndex;
	var opValue = new Array(document.book.months.Options);
	alert (opValue[opIndex]);
}

Open in new window

0
Mr_Splash
Asked:
Mr_Splash
2 Solutions
 
ZylochCommented:
Do not create a new array. Instead, do something like this:

<select name="months" id="months" onchange="updateMonth(this);">

Then, you can have

function updateMonth(sel) {
    alert(sel.options[sel.selectedIndex]);
}
0
 
Mr_SplashAuthor Commented:
Thanks Zyloch,

But I'm now getting [object HTMLOptionElement]

Implemented exactly as you specified.
0
 
erikTsomikSystem Architect, CF programmer Commented:
try this
function updateMonth(sel) {
    alert(sel.options[sel.selectedIndex].value);
}
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
ZvonkoSystems architectCommented:
Or simplified:

<select name="months" id="months" onchange="updateMonth(this);">

function updateMonth(theSel){
  alert(theSel.value);
}

0
 
ZylochCommented:
That's right. I can't believe I forgot the value attribute, thanks for the save.
0
 
erikTsomikSystem Architect, CF programmer Commented:
that is fine , but got no points anyway.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now