search

Home  >  Q&A  >  body text

Simulate the onClick event of a form selection option using the Enter key

I have a form that passes a value 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 uses the arrow keys and the Enter key to select an option.

How do I press the Enter key to pass the appropriate value to myfun()?

I've 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've tried adding onchange to select elements in the past, but had other issues. And the code that populates the options list needs to be rewritten.

P粉275883973P粉275883973318 days ago453

reply all(2)I'll reply

  • P粉616383625

    P粉6163836252024-01-17 12:40:04

    Using onChange calls will lead to duplicate code, which is not a feasible idea.

    Consider putting the data into a data- set so you can use the onChange event on select. This event is triggered when you press and while using the keyboard. So no need to duplicate code.

    Then use dataset to get the data 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);
    }
    Select
    

    reply
    0
  • P粉342101652

    P粉3421016522024-01-17 00:14:00

    Use select.onchange event instead, as shown below:

    function myfun(id,h,k){
      console.log(id,h,k)
    }
    Select

    reply
    0
  • Cancelreply