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 ?

3
  • just use .replace and remove , Commented Sep 6, 2019 at 12:17
  • where exactly ? Commented Sep 6, 2019 at 12:18
  • did you try to put e.preventDefault() at the start of your function? Commented Sep 6, 2019 at 12:18

2 Answers 2

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" />

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.