點燈坊

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

Using x-model with Textbox

Sam Xiao's Avatar 2022-01-23

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

Version

Alpine 3.9

$event

textbox000

We can use @input event and $event magic property to implement two-way data binding.

<!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="{ message: '' }">
    <input
      type="text"
      :value="message"
      @input="message = $event.target.value"
    />
    <span x-text="message" />
  </body>
</html>

Line 9

<body x-data="{ message: '' }">
  <input
    type="text"
    :value="message"
    @input="message = $event.target.value"
  />
  <span x-text="message" />
</body>
  • @input : on input event to write input value to a variable
  • $event : access the native JavaScript event object

x-model

textbox000

We can also use x-model to realize two-way data binding.

<!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="{ message: '' }">
    <input type="text" x-model="message" />
    <span x-text="message" />
  </body>
</html>

Line 9

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

Conclusion

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

Reference

Alpine, Text inputs