Reputation: 123098
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.
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?
Upvotes: 2
Views: 2214
Reputation: 29585
You forgot bind:
, so the value of draftMessage
never actually changes, so draftMessage = ''
has no effect. You have a couple of options:
<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 heredraftMessage
entirely, and use the DOM throughout (input.value = ''
). Demo hereUpvotes: 3