Index of Clicked option in multiple select

P

puneet.bansal

Hi,

I want to know the index of the option that a user clicks on in a
multiple-select object (regardless of whether he selected or deselected
it). This seems fairly simple but I can't seem to figure out how to do
it. Does anybody know how to do this?

Thanks.
Puneet
 
R

RobG

Hi,

I want to know the index of the option that a user clicks on in a
multiple-select object (regardless of whether he selected or deselected
it). This seems fairly simple but I can't seem to figure out how to do
it. Does anybody know how to do this?

Option elements can have onclick attributes and they also have in index
property, so you can do:

<option onclick="alert(this.index + ' selected? ' + this.selected);">


in browsers that conform to HTML 4 and DOM 2. However, not all browsers
fully implement these standards.

For a single select, whatever option is clicked on is selected - the
only way to de-select it is to either select some other option or reset
the select. Therefore, whatever option is selected is the one that was
clicked on - looking at the select's selectedIndex property will tell
you which option that is.

You can also use the the click event's attributes to find out what
element was clicked on (the target/srcElement for W3C/IE event models) -
but since IE doesn't seem to have an onclick attribute for options, it
tells you that event.srcElement is the select, not the option that was
clicked on.

For a multiple select and W3C compliant browser, you can use either the
options onclick attribute (preferred) or event attributes (not preferred
but helpful sometimes), but with IE you're out of luck.

Something to play with:


<script type="text/javascript">

function optClickedOn(e)
{
var e = e || window.event;
var tgt = e.target || e.srcElement;
var t = '';
if (tgt){
if (tgt.nodeName) {
t += tgt.nodeName;
}
if ('number' == typeof tgt.index) {
t += ' index ' + tgt.index + '.';
}
if ('boolean' == typeof tgt.selected) {
t += ' It is ' + ((tgt.selected)?'':'not ') + 'selected.';
}
}
document.getElementById('msg').innerHTML = t;
}

</script>

<div>You clicked on: <span id="msg"></span></div>
<select onclick="optClickedOn(event);" multiple>
<option>opt 01
<option>opt 02
<option>opt 03
</select>
<br>
<select>
<option onclick="alert(this.index);">opt 01
<option onclick="alert(this.index);">opt 02
<option onclick="alert(this.index);">opt 03
</select>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top