'on:keydown event with Enter Key in svelte

I am using svelte with a 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>


Solution 1:[1]

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

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 H.B.
Solution 2 lache