4

In the following example, when clicking on the select element and changing the value, the textarea value is set to empty.

I also have buttons that change the select value, but this does not trigger the change event and set the textarea value to empty.

<div x-data="{ select : 1, textarea : 'test' }">
    <div>
        <button x-on:click="select = 1">One</button>
        <button x-on:click="select = 2">Two</button>
        <button x-on:click="select = 3">Three</button>
    </div>

    <div>
        <select name="test" x-model="select" x-on:change="textarea = ''">
            <option value="1">One</option>
            <option value="2">Two</option>
            <option value="3">Three</option>
        </select>
    </div>
    
    <textarea name="foobar" x-model="textarea">test</textarea>    
</div>

I can get this working by updating the click events on each button, like the following.

<button x-on:click="select = 1; textarea = ''">One</button>

Is there any way to trigger the change event on the select, regardless of whether it's triggered by the button or directly changing the select value?

1 Answer 1

5

x-model will update the value without triggering a "change" event.

In your case, I assume you want "whenever select changes, reset textarea value to ''".

Which you can do using x-init and $watch('select', () => { textarea = '' }). As a bonus you don't need the x-on:change="textarea = ''" on the <select> any more.

Full example would be:

<div
  x-data="{ select : 1, textarea : 'test' }"
  x-init="$watch('select', () => { textarea = '' })"
>
    <div>
        <button x-on:click="select = 1">One</button>
        <button x-on:click="select = 2">Two</button>
        <button x-on:click="select = 3">Three</button>
    </div>

    <div>
        <select name="test" x-model="select">
            <option value="1">One</option>
            <option value="2">Two</option>
            <option value="3">Three</option>
        </select>
    </div>
    
    <textarea name="foobar" x-model="textarea">test</textarea>    
</div>
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.