alpinejs / alpine

A rugged, minimal framework for composing JavaScript behavior in your markup.
https://alpinejs.dev
MIT License
27.96k stars 1.22k forks source link

Fix fill modifier for radio buttons #4101

Closed willrowe closed 6 months ago

willrowe commented 6 months ago

This fixes filling model data based on which radio button is checked when the page loads. A very simple example can be found here and this PR also includes a test.

In the Codepen, I expected that type in the Alpine data would be set to 'second' after page load and that the 'Second' radio button would be checked. However, type is set to 'first' and the 'First' radio button is checked instead.

I did a little bit of debugging and figured out that a change event is being triggered when the .fill modifier is present. Removing it from the first radio button (second example in the Codepen) makes it work as expected, but it should still work when the modifier is present by filling based on which radio button is currently checked.

The getInputValue function has been updated to take into account whether a radio button is checked, if not it will return the currentValue. I loosely based the changes on how checkboxes are handled.

I tested it with checkboxes (third example in the Codepen) and that appears to be working correctly.

ekwoka commented 6 months ago

This is a good bug find!

Would it not be simpler to only dispatch the fill/change event on a checked radio?

Or is there another context in which a radio could dispatch a change event when unchecked?

willrowe commented 6 months ago

@ekwoka I made the least intrusive change possible. I thought the same thing about the change event, but when debugging I discovered the getInputValue function and saw that it considered checkbox groups there, so it made the most sense to consider radio button groups in the same way. You can see in that function that it checks whether checkboxes are checked when returning the value.

ekwoka commented 6 months ago

This is true. The change you made is definitely inline with the existing decisions.

calebporzio commented 6 months ago

Perfect, thanks!