Recently I was working with a web form for submitting some data. But one of the
input fields was used for searching instead, so I wanted to prevent the form
from being submitted when the user pressed enter in that field. If you have a
few forms this is possible to solve with JavaScript on every page. But I wanted
something else so I created a solution where you only need to add a CSS-class on
the fields what should have this behavior. I think this turned out to be an
elegant and reusable solution.
Overview
After my solution was ready, I could just add the class
prevent-default-on-enter on input fields and buttons like this:
HTML
And then all enter presses would be blocked from submitting the form.
The solution
I rarely work with JavaScript, so I thought this was an interesting problem. I
wanted my solution to configure itself when the page was loaded. But I also wanted
it to react to changes, both when nodes were added and when classes were changes
on nodes.
MutationObserver
is the modern solution for this, and to my knowledge this is quite efficient.
After some hours playing around with this, I had this TypeScript code:
TypeScript
Or, if you prefer pure JavaScript instead:
JavaScript
I think this should work in all modern browsers. I have done some testing in IE11 that worked well.
Example
Below is a simple page I used for testing build in a Blazor application. You
need to add the JavaScript code either on the page or reference via a
JavaScript-file. The example page both adds nodes and changes attributes on
fields:
Blazor
Summary
I am happy with this solution and I learned a lot while a was developing it.
Originally, I run into this problem working with a Razor component in an ASP.NET
Core application. First I thought it would be enough to use
@onkeypress:preventDefault on my tags. First, I discovered that nothing was
changed after I added that due a bug in the
framework. Then, after also
adding a onkeypress handler, I could get it to work but I also needed to
handle every keystroke in the input field and manually update the user
interface. I did not like that. I also found a solution on
StackOverflow
that involved triggering JavaScript code from C#, which works but it is a bit
clumsy and nothing you want to do if you have a lot of forms. Sometimes I get
surprised how much time you spend on something that should be a trivial problem.