alisanie's avatar

Stop Submiting form when Press Enter

Hi

As you can see I have a very small from. The problem Is when I press enter the form submit. I tried to fix it by using wire:keydown.enter.stop but the problem is not solved.

<form wire:submit.prevent="saveStoreData">
        <input type="text" wire:model="instagram" class="border bg-gray-500">
</form>

0 likes
10 replies
Nakov's avatar

@alisanie do you have a button with type submit within the form? I tried the same code as you shown above locally, and it is not submitting the form on enter, unless I put a submit button.

alisanie's avatar

@nakov The Code is correct. There is no submit button.I also check with submit button and the result is same.

Snapey's avatar

There must be more to it... Do you have any redirect in the component class?

Are you sure you have not nested this form inside another form?

Sinnbeck's avatar

Are you sure you are loading it though a livewire component and not just in a regular blade view returned from a regular controller?

alisanie's avatar
alisanie
OP
Best Answer
Level 12

Today I learn about implicit submission. I just add onkeydown="return event.key != 'Enter';" to my form and every thing is working.

  <form wire:submit.prevent="savePersonalData" onkeydown="return event.key != 'Enter';">
11 likes
oyepez003's avatar

You can avoid submitting the form with AlpineJS:

<form @submit.prevent>
2 likes
Joedev's avatar

With this now Enter is not working for next line in Textarea or RichEditor. Any ideas?

eEduard's avatar

I solved it with jquery. $(document).on("keydown", ":input:not(textarea)", function(event) { if (event.key == "Enter") { event.preventDefault(); } });

2 likes
TheJobGG's avatar

This solution works if you're not using jQuery:

<form wire:submit.prevent="save" onkeydown="if(event.key === 'Enter' && event.target.tagName !== 'TEXTAREA'){event.preventDefault();}">
...
</form>

It's based on the response of @alisanie but with an added condition: if the pressed key is "Enter" and the target element is not a , it prevents the form submission. Otherwise, it allows the Enter key to function normally.

Please or to participate in this conversation.