Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

on:keydown event with Enter Key in svelte

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>
like image 333
lache Avatar asked Dec 18 '25 14:12

lache


1 Answers

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 = $state('');
    let submittedValue = $state(null);
</script>

<form onsubmit={e => {
    e.preventDefault();
    submittedValue = value;
}}>
    <label>
        Search
        <input bind:value />
    </label>
    
    <button onclick={() => console.log('button clicked')}>GO</button>
</form>

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

Playground

In Svelte 3/4:

<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}

Playground

like image 92
H.B. Avatar answered Dec 21 '25 04:12

H.B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!