Categories
Mastering Development

How can I dynamically define a “value” bind in Svelte?

I’m new to Svelte, and I’m trying to use it to write a single-page app that will display a form with some field values dynamically calculated based on other fields. Ideally, I’d like to drive the rendering of the form using static JSON configuration files (to make it easy to generate new forms with other tools that output JSON).

I want to be able to dynamically define the relationships between form fields, so that when the user enters values, the computed fields recalculate automatically.

I’d like to end up with something similar to this (but obviously this doesn’t work):

<script>
let objFormConfig = JSON.parse(`{
    "formElements": [
        {
              "id": "f1",
              "label": "First value?"
        },
        {
              "id": "f2",
              "label": "Second value?"
        },
        {
               "id": "f2",
               "label": "Calculated automatically",
               "computed": "f1 + f2"
        }
    ]
}`);
</script>
<form>
{#each objFormConfig.formElements as item}
    <div>
        <label for="{item.id}">{item.label}
        {#if item.computed}
            <input type=number id={item.id} value={item.computed} readonly/>
        {:else}
            <input type=number id={item.id} bind:value={item.id}/>
        {/if}
        </label>
    </div>
{/each}
</form>

Live (non-working) REPL example here.

Can anyone point me in the right direction? Or if it’s completely impossible, could you suggest a different approach?

Leave a Reply

Your email address will not be published. Required fields are marked *