concept input in category svelte

appears as: input, inputs, n input, inputs, input
Svelte and Sapper in Action

This is an excerpt from Manning's book Svelte and Sapper in Action.

The input HTML element is an example of an empty element, which means it cannot have child nodes. When empty elements are used in Svelte components, they do not need to be terminated with />. However, if Prettier is used to format the code, it will change empty elements so they’re terminated this way. This is why some code examples in this book show terminated empty elements.

Now we can enter a name, but it doesn’t change the greeting. We need to add event handling so the value of the name variable is updated when the user types in the input. We can do this using an inline arrow function or a reference to a function defined in the script element. Change the input to the following:

Another use is to retrieve data needed by a component from API services. For example, a component that displays information about employees at a company can use an onMount function to obtain the data and store it in a top-level variable so it can be rendered. Section 8.2.2 shows an example of this.

<script>
  import {afterUpdate, beforeUpdate} from 'svelte';

  let input, name, selectionEnd, selectionStart;

  beforeUpdate(() => {
    if (input) ({selectionStart, selectionEnd} = input);          #1
  })

  afterUpdate(() => {
    input.setSelectionRange(selectionStart, selectionEnd);
    input.focus();
  });
</script>

<input bind:this={input} bind:value={name}>                       #2
<button on:click={() => name = name.toUpperCase()}>UPPER</button>