简体   繁体   中英

Blur event is firing on keydown

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM