Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(input): prevent enter to submit form #691

Merged
merged 2 commits into from
Aug 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/components/input/bl-input.stories.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,16 @@ When you run this example and submit the form, you'll see key/value pairs of the

<bl-alert icon>If user presses `Enter` key in an input inside a form, this will trigger submit of the form. This behaviour mimics the native input behaviour.</bl-alert>

If you want to prevent input to submit the form, you can listen `keydown` event and prevent it's default behaviour.

```js
document.querySelector('bl-input').addEventListener('keydown', (event) => {
if (event.code === "Enter") {
event.preventDefault();
}
});
```

## Input Masking

Input masking is essential in user interfaces that require formatted entries such as phone numbers and dates, ensuring consistent and structured user input.
Expand Down
29 changes: 29 additions & 0 deletions src/components/input/bl-input.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,35 @@ describe("bl-input", () => {

expect(ev).to.exist;
});

it("should not submit if keydown event is prevented", async () => {
const form = await fixture<HTMLFormElement>(html`<form novalidate>
<bl-input name="user" value="name"></bl-input>
<button type="submit">Submit</button>
</form>`);

const blInput = form.querySelector<BlInput>("bl-input");

blInput?.addEventListener("keydown", e => e.preventDefault());

await elementUpdated(form);

let eventFired = false;

form.addEventListener("submit", e => {
e.preventDefault();
eventFired = true;
});

const enterEvent = new KeyboardEvent("keydown", {
code: "Enter",
cancelable: true,
});

blInput?.dispatchEvent(enterEvent);

expect(eventFired).to.be.false;
});
});

describe("loading state and custom icons", () => {
Expand Down
6 changes: 5 additions & 1 deletion src/components/input/bl-input.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,11 @@ export default class BlInput extends FormControlMixin(LitElement) {

private onKeydown = (event: KeyboardEvent): void => {
if (event.code === "Enter" && this.form) {
submit(this.form);
setTimeout(() => {
if (!event.defaultPrevented) {
submit(this.form);
}
});
}
};

Expand Down
Loading