Jump to content

Sending a selected item from a list box to a javascript function


khaos337

Recommended Posts

I am trying to send a selected item from a list box to a javascript function, however I'm having problems getting the most recent selected item to be sent. For example, let's say I have a simple list box:

<select multiple="multiple" onchange="lastselected(this.value)"><option value="1">1</option><option value="2">2</option><option value="3">3</option></select>

And my javacript function is:

<script type="text/javascript">function lastselected(value){alert(value);}</script>

My problem is this. Using the "this.value" reference always sends the first (by first i mean highest in the list) value selected, not the most recent value selected. What do i need to use to get it to send a value of "3" to the function if i first select "1", then press ctrl and select "3" as well.Any help here would be greatly appreciated!

Link to comment
Share on other sites

You are using "this" to refer to the SELECT element. You need to attach the function to the <option> elements.

window.onload = function() {	options = document.getElementsByTagName('option');	for ( i = 0; i < options.length; i++ ) {   // loop through the option elements		options[i].onclick = function() {		// when the option is clicked, alert its value			alert(this.value);		} 	}}

It isn't an ideal example, but it should work.

Link to comment
Share on other sites

I am trying to send a selected item from a list box to a javascript function, however I'm having problems getting the most recent selected item to be sent. For example, let's say I have a simple list box:
<select multiple="multiple" onchange="lastselected(this.value)"><option value="1">1</option><option value="2">2</option><option value="3">3</option></select>

And my javacript function is:

<script type="text/javascript">function lastselected(value){alert(value);}</script>

My problem is this. Using the "this.value" reference always sends the first (by first i mean highest in the list) value selected, not the most recent value selected. What do i need to use to get it to send a value of "3" to the function if i first select "1", then press ctrl and select "3" as well.Any help here would be greatly appreciated!

what's weird is I'm using the exact same technique on my site and it works.
Link to comment
Share on other sites

select.value is an HTML5 property. I believe it was originally an IE standard, but that might be wrong. I'm under the impression that all current browsers support it, but I know that many older browsers do not.this.options[this.selectedIndex].value always works when this refers to the select element.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...