Binding Input Value Using Svelte

Binding Input Value Using Svelte

Svelte has so many perks that make working with it so easy and fast. One of the best parts of working with Svelte so far for me is bindings, yes input bindings are what I am talking about **inserts dancing emoji.

What are Bindings in Svelte?

So first thing first, let's understand what input binding is. Binding typically updates the value of a variable in an Input element as well as the value of the input - seems confusing yeah? Let's break it down a bit;

Say you have an input element for a user to enter their first name like this, so our input value will be whatever firstName is.

<script>
    let firstName = '';
</script>

<input type='text' value={firstName} />
<p>Hi! My name is {firstName}</p>

Now notice how if we type anything into the input field it will not work. Well that's because we are updating the value but not the variable firstName, to do that we need to add an event handler to get the event.target.value and update firstName but Svelte has provided a cleaner and easier way to update the value, all we need to do is add bind before the value attribute.

<script>
    let firstName = '';
</script>

<input type='text' bind:value={firstName} />
<p>Hi! My name is {firstName}</p>

And voila, easy peasy lemony squeezy. So now any time you are working with any input element all you need to add is bind and that will do the heavy lifting for you.

Now if you are working with group inputs; radio buttons, and checkboxes you can use bind:group along with the value attribute.

<script>
    let addOns = [];
</script>

{#each ['online service', 'larger storage', 'customizable storage'] as addOn}
    <input type='checkbox' id={addOn} value={addOn} bind:group={addOns} />
    <label for={addOn}>{addOn}</label>
{/each}