1

i'm trying to make tag input and when user type ',' character i wan't to add entry to input

i use for it like that function on onKeyDown

inputKeydown = e => {
    const val = e.target.value;
    var patt = /^[0-9]*$/;
    if (e.key === "Enter" ||  e.which === 188 && val) {
      let a = this.state.zips.includes(val);
      if (
        this.state.tags.find(
          tag => tag.value.toLowerCase() === val.toLowerCase()
        )
      ) {
        return;
      }
      if (val.length != 5) {
        return;
      }
      this.setState({ tags: [...this.state.tags, { match: a, value: val }] });
      this.tagInput.value = null;
    } else if (e.key === "Backspace" && !val) {
      this.removeTag(this.state.tags.length - 1);
    }
  };

here is if user press to enter entry goes to this.state.tags array here i wan't to do if user type ',' will be same action.

i used for that

e.which === 188

everything works well but this add to input ',' character too. i don't wan't to show ',' character in input what i need to do ?

user3348410
  • 2,733
  • 10
  • 51
  • 85

2 Answers2

3

Simply use e.preventDefault() in your condition so that the default event (inserting a comma) is not triggered

document.getElementById('textinput').addEventListener('keydown', e => {
  if(e.which === 188){
    alert('comma')
    e.preventDefault()
  }
})
<input type="text" id="textinput" />
BJRINT
  • 639
  • 3
  • 8
1

Use preventDefault() method. From the MDN:

This method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.

So:

inputKeydown = e => {
    const val = e.target.value;
    var patt = /^[0-9]*$/;
    if (e.key === "Enter" ||  e.which === 188 && val) {
      e.preventDefault(); // ---> This will prevent putting a comma.
      let a = this.state.zips.includes(val);
      if (
        this.state.tags.find(
          tag => tag.value.toLowerCase() === val.toLowerCase()
        )
      ) {
        return;
      }
      if (val.length != 5) {
        return;
      }
      this.setState({ tags: [...this.state.tags, { match: a, value: val }] });
      this.tagInput.value = null;
    } else if (e.key === "Backspace" && !val) {
      this.removeTag(this.state.tags.length - 1);
    }
  };

You also could have use return false which does the same thing with some additional stuff. Please see this great response for more details.

alioguzhan
  • 7,657
  • 10
  • 46
  • 67