By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,949 Members | 889 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,949 IT Pros & Developers. It's quick & easy.

Index of Clicked option in multiple select

P: n/a
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

Jan 20 '06 #1
Share this Question
Share on Google+
1 Reply


P: n/a
pu***********@wipro.com wrote:
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>

--
Rob
Jan 22 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.