Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

to call onChange event after pressing Enter key

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 }); 
like image 894
Bill Lumbert Avatar asked Jul 07 '15 14:07

Bill Lumbert


People also ask

How do you get Enter key event in React?

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.

What is the type of onChange event?

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.


Video Answer


2 Answers

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} /> } 
like image 89
wuct Avatar answered Oct 06 '22 02:10

wuct


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()                 }               }} /> 
like image 20
Admir Avatar answered Oct 06 '22 02:10

Admir