點燈坊

失くすものさえない今が強くなるチャンスよ

Using x-model with Checkbox

Sam Xiao's Avatar 2022-01-23

We can implement two-way data binding with <input type="checkbox"> by x-model.

Version

Alpine 3.9

x-model

checkbox000

The checkbox is two-way binding to a variable.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://unpkg.com/alpinejs" defer></script>
    <title>Alpine</title>
  </head>
  <body x-data="{ isChecked: false }">
    <input type="checkbox" x-model="isChecked" />
    <span x-text="isChecked" />
  </body>
</html>

Line 9

<body x-data="{ isChecked: false }">
  <input type="checkbox" x-model="isChecked" />
  <span x-text="isChecked" />
</body>
  • x-model : two-way data binding the checked value to a variable
  • x-text : display the value of a variable

Conclusion

  • <input type="checkbox"> is two-way data binding to a boolean variable by x-model

Reference

Alpine, Checkbox inputs