I have a form that passes values to a function.
<TR><TD>Select</TD><TD><select name=k_id>
<OPTION value=1 onClick="myfun('10','0.1','1')">Option 1</OPTION>
<OPTION value=2 onClick="myfun('20','0.2','2')">Option 2</OPTION>
<OPTION value=3 onClick="myfun('30','0.3','3')">Option 3</OPTION>
<OPTION value=4 onClick="myfun('40','0.4','4')">Option 4</OPTION>
</select>
function myfun(id,h,k,g)
{
var h_id=document.getElementById('h_id');
h_id.value=id;
var hind=document.getElementById('hind');
hind.value=h;
var koe=document.getElementById('koe');
koe.value=k;
}
But it doesn’t work if the user selects an option using arrow keys and Enter.
How can I pass appropriate values to myfun() with pressing Enter?
I have tried:
<OPTION value=1 onClick="myfun('10','0.1','1')" onkeypress="if(event.key == 'Enter') {myfun('10','0.1','1')}">Option 1</OPTION>
<OPTION value=1 onClick="myfun('10','0.1','1')" onkeyup = "if(event.keyCode == 13){myfun('10','0.1','1')}">Option 1</OPTION>
<OPTION value=1 onClick="myfun('10','0.1','1')" onkeydown = "if(event.keyCode == 13){myfun('10','0.1','1')}">Option 1</OPTION>
I have tried adding onchange to select element in the past but that had other issues. And would require rewriting the code that populates options list.
2
Answers
Use the select.onchange event instead, like this:
This answer attempted to listen for clicks, and it seems like it worked at the time. But it doesn’t work in the current version of Chrome.
Using the
onChange
call will result in a duplicate code, and more unreable thinks.Consider placing your data in
data-
sets, so you can use aonChange
event on theselect
. This event will trigger when your press and when you use your keyboard. So no need to duplicate code.Then use
dataset
to get your data back from the new value: