Skip to content

Commit

Permalink
feat(input): prevent enter to submit form
Browse files Browse the repository at this point in the history
  • Loading branch information
muratcorlu authored and Davut Enes Yıldırım committed Aug 5, 2024
1 parent 60ffde6 commit 7b230b0
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
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
2 changes: 1 addition & 1 deletion src/components/input/bl-input.ts
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ export default class BlInput extends FormControlMixin(LitElement) {
}

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

0 comments on commit 7b230b0

Please sign in to comment.