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 });
Let us create a React project and then we will create a UI that takes input from users. Users can interact with the UI and press Enter Key to trigger an event through this. We will be creating an input field that takes the message as input.
The onchange event occurs when the value of an element has been changed. For radiobuttons and checkboxes, the onchange event occurs when the checked state has been changed.
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'); } } });
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.
const Input = () => { const handleKeyDown = (event) => { if (event.key === 'Enter') { console.log('do validate') } } return <input type="text" onKeyDown={handleKeyDown} /> }
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() } }} />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With