You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决在Laravel 8+TailwindCSS 2+AlpineJS 2.8项目中通过ID为表单绑定按键事件时的TypeError错误?

Fixing the AlpineJS/Vanilla JS Form Keypress Handler Issue

Hey there! Let's sort out that error you're seeing. The problem is pretty straightforward: that .on() method you're using is a jQuery-specific function, but you're calling it on a native DOM element (not a jQuery-wrapped object) — which is why you get the "on is not a function" error.

Here are two clean, correct ways to handle this, tailored to your AlpineJS/Vanilla JS setup:

Option 1: Native JavaScript addEventListener

Since you're already grabbing the form element with querySelector, replace the jQuery-style .on() with native addEventListener. You can even simplify by using a single keydown event (it covers both keyup/keypress scenarios for preventing Enter):

let form_ad_location_edit = document.querySelector("#form_ad_location_edit");
form_ad_location_edit.addEventListener('keydown', function(e) {
  const keyCode = e.keyCode || e.which;
  if (keyCode === 13) {
    e.preventDefault();
    return false;
  }
});

Since you're using AlpineJS, why leverage its declarative syntax to avoid manual DOM manipulation entirely? Just add the @keydown.enter.prevent directive directly to your form tag:

<form 
  action="{{ route('admin.ads.ad_locations.'. ( $isInsert ? 'store' : 'update'), [1, ( $adLocation->id ?? '' ), 1 ] ) }}" 
  method="POST" 
  id="form_ad_location_edit" 
  enctype="multipart/form-data"
  x-data
  @keydown.enter.prevent
>
<!-- Your form fields here -->
</form>

This does exactly what you need: prevents the form from submitting when the Enter key is pressed, and it's way cleaner than writing vanilla JS listeners. The x-data attribute just initializes Alpine on the form element so the directive works.

Why Your Original Code Failed

To recap: when you use document.querySelector(), you get a native HTMLFormElement object. jQuery's .on() is a method that only exists on jQuery-wrapped objects (like what you get from $('#form_ad_location_edit')). Since you're not using jQuery, that method doesn't exist on the native element — hence the error.

内容的提问来源于stack exchange,提问作者mstdmstd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 12:12:30