如何解决在Laravel 8+TailwindCSS 2+AlpineJS 2.8项目中通过ID为表单绑定按键事件时的TypeError错误?
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; } });
Option 2: AlpineJS Declarative Directive (Recommended)
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

