skip to Main Content

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


  1. Use the select.onchange event instead, like this:

    function myfun(id,h,k){
      console.log(id,h,k)
    }
    <TR><TD>Select</TD><TD><select name=k_id onchange="myfun(...JSON.parse(this.value))">
    <OPTION  value='["10","0.1","1"]'>Option 1</OPTION>
    <OPTION  value='["20","0.2","2"]'>Option 2</OPTION>
    <OPTION  value='["30","0.3","3"]'>Option 3</OPTION>
    <OPTION  value='["40","0.4","4"]'>Option 4</OPTION>
    </select>

    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.

    Login or Signup to reply.
  2. 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 a onChange event on the select. 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:

    function myfun(event) {
        const e = event.target;
        const { id, h, k } = e.options[e.selectedIndex].dataset;
        
        console.log('Change: ', id, h, k);
    }
    <TR><TD>Select</TD><TD>
    <select name="k_id" onChange='myfun(event)'>
        <OPTION  value=1 data-id='10' data-h='0.1' data-k='1'>Option 1</OPTION>
        <OPTION  value=2 data-id='20' data-h='0.2' data-k='2'>Option 2</OPTION>
        <OPTION  value=3 data-id='30' data-h='0.3' data-k='3'>Option 3</OPTION>
        <OPTION  value=4 data-id='40' data-h='0.4' data-k='4'>Option 4</OPTION>
    </select>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search