Ryan
Ryan

Reputation: 1338

Trigger change event after click event in alpine.js

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?

Upvotes: 4

Views: 21408

Answers (1)

Hugo
Hugo

Reputation: 3888

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>

Upvotes: 5

Related Questions