Skip to content
Advertisement

Capture value from an input with svelte

I’m trying to capture the value of an input using the svelte framework

<script>
   var name = document.getElementById("#name");
   var valueName = name.value;

   function showName(){
       console.log(valueName);
   }
</script>

<main>
    <div>
        <input id="name" type="text"">
        <button type="submit" on:click={showName}>Send</button>
    </div>
</main>

When initializing the local environment I already get the following error in the console:

Uncaught TypeError: Cannot read properties of null (reading ‘value’)

Visual Studio Code marks the code snippet .value when I try to capture the input value with the error:

Property ‘value’ does not exist on type ‘HTMLElement’

What is the correct way to capture the value typed in an input with Svelte ?

Advertisement

Answer

  1. You are generally not supposed to query the DOM when using Svelte
  2. It is not safe to access the DOM until the component has been mounted (the elements will not exist yet)

You should use bind:this when you need a DOM element, it will usually be available in DOM events and in the onMount lifecycle function. In general, directly accessing the DOM should be avoided.

In this case you can just bind the value:

<script>
   let valueName;

   function showName() {
       console.log(valueName);
   }
</script>

<input id="name" type="text" bind:value={valueName}>
<button type="submit" on:click={showName}>Send</button>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement