Tracking Input Change in Alpine. Js

I'm learning alpine.js and trying to capture the user input value. I have used "x-on:input" but its not calling the function

Below is the simple form input

 <input type="email" class="form-control" x-on:input.debounce="validateEmail($event)" x-model="userEmail" id="email" aria-describedby="emailHelp" placeholder="Enter email">

and this is the basic method in my index.js

function validateEmail(event){
console.log(userEmail);

}

The function is not getting called.

Adding a sample stackblitz

Please Guide

Thanks Shruti Nair

1 Answer

You're looking for x-on:change

<input type="email" class="form-control" x-on:change.debounce="validateEmail($event)" x-model="userEmail" id="email" aria-describedby="emailHelp" placeholder="Enter email">

You'll also want to make your function read the value from $event.target.value

Since you've already got an x-model, you could add $watch('userEmail', (val) => {}) to x-init and validate that way.

Edit: (based on the stackblitz)

  • x-data is missing
  • I've inlined all the logic from index.js
  • forked stackblitz at

Full component:

<form x-data="{
  userEmail: '',
  validateEmail(event) {
    console.log(event.target.value);
  },
  submit($event) {
    console.log(this.userEmail)
  }
}">
  <input type="email"  class="form-control"
    x-on:change.debounce="validateEmail($event)"
    x-model="userEmail"
    id="email"
    aria-describedby="emailHelp"
    placeholder="Enter email"/>
  <button type="button" x-on:click="submit" class="btn btn-block">
    Submit
  </button>
</form>
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest