Reputation: 87
I need to get an input value on enter press and also on blur event. So I have created 2 functions:
<input @blur=${this._setNameByBlur} @keydown=${this._setNameByEnter}/>
Handling blur event
byBlur(e) {
const text = e.currentTarget.value;
e.preventDefault();
this.dispatchEvent(new CustomEvent("save-entry", { detail: text, composed: true, bubbles: true}));
}
Handling enter key press
byEnter(e) {
const text = e.currentTarget.value;
if (e.type === "keydown") {
if (e.key === 'Enter' || e.keyCode === 13) {
e.preventDefault();
e.stopPropagation();
this.dispatchEvent(new CustomEvent("save-entry", { detail: text, composed: true, bubbles: true}));
}
}
}
The problem is that when I'm pressing "enter" key, besides executing byBlur
function, there is also executing byEnter
- I think it's happens basically because on enter press, I'm actually losing focus, so that's why. Looking for a key to fix that issue
Upvotes: 1
Views: 1786
Reputation: 133
how about call blur()
in byEnter
byEnter(e) {
if (e.type === "keydown") {
if (e.key === 'Enter' || e.keyCode === 13) {
e.preventDefault();
e.stopPropagation();
e.target.blur();
}
}
}
Upvotes: 0
Reputation: 87
this is what i come up
_setNameByBlur(e) {
const text = e.currentTarget.value.trim();
if (e.sourceCapabilities !== null) {
e.preventDefault();
this.dispatchEvent(new CustomEvent("save-entry", { detail: text, composed: true, bubbles: true}));
}
}
when blur event is firing after "enter" press its "null".
so i have just added a condition
Upvotes: 0