I want to handle the change event of a select element depending on whether the CTRL-Key is pressed, but it does not work.
Here's what I have: An ASP.NET WebForms ListBox control (that renders to a select element with options like so (slightly simplified):
<select name="ctl00$ContentPlaceHolder1$MultiselectDropDownStatus" id="ctl00_ContentPlaceHolder1_MultiselectDropDownStatus" size="7" multiple="multiple">
<option selected="selected" value="">All</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
Now, when the user selects one option, I want to do something depending on the state of the CTRL-Key. I will handle the change event like so:
script.AppendLine(@" $(""#" + ClientID + @""").change(function (e) {");
//....
Inside the script method I want to check the key state
script.AppendLine(@" if (e.ctrlKey) {");
script.AppendLine(@" alert(""ctr key was pressed during the click"")");
script.AppendLine(@" }");
//...
However, this way, the e.crtlKey
is always undefined
.
But, when I handle the click event of the listbox control directly (not via the change event), like so:
script.AppendLine(@" $(""#" + ClientID + @""").click(function (e) {");
script.AppendLine(@" if (e.ctrlKey) {");
script.AppendLine(@" alert(""ctr key was pressed during the click"")");
script.AppendLine(@" }");
Here, the e.crtlKey
gives me the correct value.
Why can I not get the CTRL-Key state correctly in the change handler?
I am working with IE 11 right now, but it should also work on other major browsers.
Update: Originally I wanted to handle the event of having multiple selections using the CTRL key state. I realised that this was wrong and now I have solved this by explicitly counting the selected options. However, this question remains valid, and thus I will leave it here: How to detect the key state in the changed handler?
You cannot. The change event does not define ctrlKey
, as you have noted.
change is an event which uses the base event interface, which does not handle ctrlKey
.
To have ctrlKey
defined, you need to use a TouchEvent, MouseEvent, or KeyboardEvent.
In your example, click
leads to change
being triggered. click
, being a MouseEvent, has the ctrlKey
information, but change
does not.
If desired you could have a global variable updated in the click event which would indicate if ctrlKey was pressed and then use that within the change event.