to call onChange event after pressing Enter key

Bill Lumbert picture Bill Lumbert · Jul 7, 2015 · Viewed 277.7k times · Source

I am new to Bootstrap and stuck with this problem. I have an input field and as soon as I enter just one digit, the function from onChange is called, but I want it to be called when I push 'Enter when the whole number has been entered. The same problem for the validation function - it calls too soon.

var inputProcent = React.CreateElement(bootstrap.Input, {type: "text",
  //bsStyle: this.validationInputFactor(),
  placeholder: this.initialFactor,
  className: "input-block-level",
  onChange: this.handleInput,
  block: true,
  addonBefore: '%',
  ref:'input',
  hasFeedback: true
});

Answer

wuct picture wuct · Jul 7, 2015

According to React Doc, you could listen to keyboard events, like onKeyPress or onKeyUp, not onChange.

var Input = React.createClass({
  render: function () {
    return <input type="text" onKeyDown={this._handleKeyDown} />;
  },
  _handleKeyDown: function(e) {
    if (e.key === 'Enter') {
      console.log('do validate');
    }
  }
});

Update: Use React.Component

Here is the code using React.Component which does the same thing

class Input extends React.Component {
  _handleKeyDown = (e) => {
    if (e.key === 'Enter') {
      console.log('do validate');
    }
  }

  render() {
    return <input type="text" onKeyDown={this._handleKeyDown} />
  }
}

Here is the jsfiddle.

Update 2: Use a functional component

const Input = () => {
  const handleKeyDown = (event) => {
    if (event.key === 'Enter') {
      console.log('do validate')
    }
  }

  return <input type="text" onKeyDown={handleKeyDown} />
}