最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Tracking input change in alpine.js - Stack Overflow

programmeradmin3浏览0评论

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

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

Share Improve this question edited Jan 18, 2021 at 2:50 Shruti Nair asked Jan 14, 2021 at 7:03 Shruti NairShruti Nair 2,0349 gold badges32 silver badges60 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 12

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 https://stackblitz./edit/web-platform-alpinejs-prwaeg?file=index.html

Full ponent:

<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>
发布评论

评论列表(0)

  1. 暂无评论