2

I have a simple demo app of binding an input using Svelte. This works, but during a click handler on that same element, I wish to reset the bound value.

enter image description here

Specifically I have bound an input to draftMessage and would like to set draftMessage back to an empty string after the message is submitted:

<script>

    let draftMessage = '';

    let handleSendMessageClick = function(event){
        var message = event.target.form.querySelector('input').value
        previousMessages.push(message)
        previousMessages = previousMessages

        // Clear draftMessage
        console.log(`Clearing draftMessage - why doesn't this work?`)
        draftMessage = ''
    }

    let previousMessages = [];
</script>

<h1>Type some things</h1>

<form>
  <input value={draftMessage}/>
  <button on:click|preventDefault={handleSendMessageClick}>Send</button>
</form>

{#each previousMessages as message}
  <p>{message}</p>
{/each}

There is a live demo here

How can I change a bound value in a click handler?

1 Answer 1

3

You forgot bind:, so the value of draftMessage never actually changes, so draftMessage = '' has no effect. You have a couple of options:

  1. Do <input bind:value={draftMessage}> so that by the time you hit that line, draftMessage has a value other than the empty string. (You can now use that value instead of querying the DOM — previousMessages = [...previousMessages, draftMessage]). Demo here
  2. Skip draftMessage entirely, and use the DOM throughout (input.value = ''). Demo here
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.