Garfield Lasaga
Garfield Lasaga

Reputation: 418

Alpine.js how to watch for changes for radio button

Suppose I have this html and I want to do something each time user changes the pet:

<input type="radio" id="cat" name="pet" value="cat">
<input type="radio" id="dog" name="pet" value="dog">

I tried this way:

<input type="radio" id="cat" :change="onPetChange('pet', 'cat')" name="pet" value="cat">
<input type="radio" id="dog" :change="onPetChange('pet', 'dog')"  name="pet" value="dog">

But that doesn't work, it just output all values and calls the onPetChange() twice.

Upvotes: 6

Views: 14456

Answers (3)

alex
alex

Reputation: 111

This works perfect:

<script src="https://cdn.jsdelivr.net/gh/alpinejs/[email protected]/dist/alpine.min.js"></script>
<div x-data="{res: ''}">
<input type="radio" id="cat" @change="console.log(res)" name="pet" value="cat" x-model="res">
<label for="cat">Cat</label><br>
<input type="radio" id="dog" @change="console.log(res)"  name="pet" value="dog"  x-model="res">
<label for="dog">Dog</label><br>
<p x-text="res"></p>
</div>

Upvotes: 3

keyboardSmasher
keyboardSmasher

Reputation: 2811

You can x-model the radio value, then watch for changes to the value, and then do something. In this case, just console.log

<div x-data="{pet: ''}" x-init="$watch('pet', value => console.log(value))">
  <input type="radio" id="cat" value="cat" x-model="pet">
  <input type="radio" id="dog" value="dog" x-model="pet">
  <p>Pet: <span x-text="pet"></span></p>
</div>

<script src="https://cdn.jsdelivr.net/gh/alpinejs/[email protected]/dist/alpine.min.js"></script>
<div x-data="{pet: ''}" x-init="$watch('pet', value => console.log(value))">
  <input type="radio" id="cat" value="cat" x-model="pet">
  <input type="radio" id="dog" value="dog" x-model="pet">
  <p>Pet: <span x-text="pet"></span></p>
</div>

Upvotes: 9

Mellgood
Mellgood

Reputation: 325

I think you have a typo on your HTML tag. It should be "onchange" and not ":change".

As you have not provided your onPetChange function, I do not know if it could be also a problem for you. Have you got that function in place?

Anyways here it is a script that prints on your console "hello world" when you select the first radio button.

Try with:

<input type="radio" id="cat" :change="console.log('Hello World!')" name="pet" value="cat">
<input type="radio" id="dog" onchange="onPetChange('pet', 'dog')"  name="pet" value="dog">

If you provide us also your onPetChange function I can have a look on it to check if there is something wrong with it too.

Upvotes: 0

Related Questions