Home » Reactjs » to call onChange event after pressing Enter key

to call onChange event after pressing Enter key

Posted by: admin November 30, 2017 Leave a comment

Questions:

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
        });

Thanks!

Answers:

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

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

Here is the jsfiddle for this code.

Update: Use React.Component

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

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

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

Questions:
Answers:

pressing Enter when the focus in on a form control (input) normally triggers a submit (onSubmit) event on the form itself (not the input) so you could bind your this.handleInput to the form onSubmit.

Alternatively you could bind it to the blur (onBlur) event on the input which happens when the focus is removed (e.g. tabbing to the next element that can get focus)

Questions:
Answers:

You can use onKeyPress directly on input field. onChange function changes state value on every input field change and after Enter is pressed it will call a function search().

<input
    type="text"
    placeholder="Search..."
    onChange={event => {this.setState({query: event.target.value})}}
    onKeyPress={event => {
                if (event.key === 'Enter') {
                  this.search()
                }
              }}
/>