10

I am using svelte with an on:click event on a button. When this button is clicked, I dispatch some information to a higher component. What I would like to do is hit the enter key instead, but on:keydown doesn't seem to work? How can I get this to fire when hitting enter?

<button on:click={() => 
   dispatch('search', { searchword: item })}
>ClickMe</button>
<button on:keydown={() => 
   dispatch('search', { searchword: item })}
>PressEnter</button>
Alicia Sykes
  • 5,997
  • 7
  • 36
  • 64
lache
  • 608
  • 2
  • 12
  • 29
  • 1
    Enter already causes the `click` event by default. Having buttons that cannot be clicked violates user expectations. – H.B. Apr 27 '22 at 15:07
  • I see, so then there must be another issue I am not seeing. probably my x state management – lache Apr 27 '22 at 15:17
  • well, does the button have focus? – H.B. Apr 27 '22 at 15:18
  • 1
    I am thinking that is what is wrong, it probably doesn't – lache Apr 27 '22 at 15:18
  • usually for searches you have a `
    ` containing an `` and a `
    – H.B. Apr 27 '22 at 15:19
  • excellent! this is someone elses code so I will look into it but that helps alot. its weird cuz when i click the button it works but not on enter – lache Apr 27 '22 at 15:22

2 Answers2

9

Enter will automatically fire click if the button has focus or is part of a form and is clicked implicitly as part of the form submission.

Generally I would recommend using a form, then Enter within an <input> will cause a form submission. One can then also directly work with the form's submit event, as that may need cancelling anyway, unless the page reload is desired.

Example:

<script>
    let value = '';
    let submittedValue = null;
</script>

<form on:submit|preventDefault={() => submittedValue = value}>
    <label>
        Search
        <input bind:value />
    </label>
    
    <button on:click={() => console.log('button clicked')}>GO</button>
</form>

{#if submittedValue != null}
    <p>Submitted: {submittedValue}</p>
{/if}

REPL

H.B.
  • 166,899
  • 29
  • 327
  • 400
  • Thank you, I am finding that this button is not part of a form, and they are using x state to navigate and give focus to things. Its more complicated than I thought. – lache Apr 27 '22 at 15:43
  • This should be the accepted answer - very clearly described, and after testing against your scenario seems to work perfectly. – Alicia Sykes Jan 01 '23 at 00:27
-2

The issue was a state machine giving focus/ not giving focus. This project was using xstate to manage alot.

lache
  • 608
  • 2
  • 12
  • 29