to call onChange event after pressing Enter key

JavascriptTwitter BootstrapReactjs

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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()
                }
              }}
/>

Solution 3 - Javascript

Pressing Enter in a form control (input) normally triggers a submit (onSubmit) event on the form. Considering that you can handle it this way (having a submit button is optional if you have only one input):

const { useState } = React;

function App() {
  const [text, setText] = useState("");
  const [submitted, setSubmitted] = useState('');

  function handleChange(e) {
    setText(e.target.value);
  }

  function handleSubmit(e) {
    e.preventDefault();
    setSubmitted(text);
    setText("");
  }

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input type="text" value={text} onChange={handleChange} />
        <input type="submit" value="add" />
      </form>
      submitted: {submitted}
    </div>
  );
}

ReactDOM.render(<App/>, document.getElementById('root'));

<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
<div id="root"></div>

Implicit form submission (submit event on Enter) is performed when:

  • there's a submit button
  • there're no submit buttons, but there's only one input

More on it here.

Alternatively you could bind your handler 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).

Solution 4 - Javascript

You can use event.key

function Input({onKeyPress}) {
  return (
    <div>
      <h2>Input</h2>
      <input type="text" onKeyPress={onKeyPress}/>
    </div>
  )
}

class Form extends React.Component {
  state = {value:""}

  handleKeyPress = (e) => {
    if (e.key === 'Enter') {
      this.setState({value:e.target.value})
    }
  }

  render() {
    return (
      <section>
        <Input onKeyPress={this.handleKeyPress}/>
        <br/>
        <output>{this.state.value}</output>
      </section>
    );
  }
}

ReactDOM.render(
  <Form />,
  document.getElementById("react")
)

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="react"></div>

Solution 5 - Javascript

React users, here's an answer for completeness.

> React version 16.4.2

You either want to update for every keystroke, or get the value only at submit. Adding the key events to the component works, but there are alternatives as recommended in the official docs.

Controlled vs Uncontrolled components

Controlled

From the Docs - Forms and Controlled components:

> In HTML, form elements such as input, textarea, and select typically > maintain their own state and update it based on user input. In React, > mutable state is typically kept in the state property of components, > and only updated with setState(). > > We can combine the two by making the React state be the “single source > of truth”. Then the React component that renders a form also controls > what happens in that form on subsequent user input. An input form > element whose value is controlled by React in this way is called a > “controlled component”.

If you use a controlled component you will have to keep the state updated for every change to the value. For this to happen, you bind an event handler to the component. In the docs' examples, usually the onChange event.

Example:

  1. Bind event handler in constructor (value kept in state)

    constructor(props) { super(props); this.state = {value: ''};

     this.handleChange = this.handleChange.bind(this);
    

    }

  2. Create handler function

    handleChange(event) { this.setState({value: event.target.value}); }

  3. Create form submit function (value is taken from the state)

    handleSubmit(event) { alert('A name was submitted: ' + this.state.value); event.preventDefault(); }

  4. Render

If you use controlled components, your handleChange function will always be fired, in order to update and keep the proper state. The state will always have the updated value, and when the form is submitted, the value will be taken from the state. This might be a con if your form is very long, because you will have to create a function for every component, or write a simple one that handles every component's change of value.

Uncontrolled

From the Docs - Uncontrolled component

> In most cases, we recommend using controlled components to implement > forms. In a controlled component, form data is handled by a React > component. The alternative is uncontrolled components, where form data > is handled by the DOM itself. > > To write an uncontrolled component, instead of writing an event > handler for every state update, you can use a ref to get form values > from the DOM.

The main difference here is that you don't use the onChange function, but rather the onSubmit of the form to get the values, and validate if neccessary.

Example:

  1. Bind event handler and create ref to input in constructor (no value kept in state)

    constructor(props) { super(props); this.handleSubmit = this.handleSubmit.bind(this); this.input = React.createRef(); }

  2. Create form submit function (value is taken from the DOM component)

    handleSubmit(event) { alert('A name was submitted: ' + this.input.current.value); event.preventDefault(); }

  3. Render

If you use uncontrolled components, there is no need to bind a handleChange function. When the form is submitted, the value will be taken from the DOM and the neccessary validations can happen at this point. No need to create any handler functions for any of the input components as well.

Your issue

Now, for your issue:

> ... I want it to be called when I push 'Enter when the whole number has been entered

If you want to achieve this, use an uncontrolled component. Don't create the onChange handlers if it is not necessary. The enter key will submit the form and the handleSubmit function will be fired.

Changes you need to do:

Remove the onChange call in your element

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

Handle the form submit and validate your input. You need to get the value from your element in the form submit function and then validate. Make sure you create the reference to your element in the constructor.

  handleSubmit(event) {
      // Get value of input field
      let value = this.input.current.value;
      event.preventDefault();
      // Validate 'value' and submit using your own api or something
  }

Example use of an uncontrolled component:

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    // bind submit function
    this.handleSubmit = this.handleSubmit.bind(this);
    // create reference to input field
    this.input = React.createRef();
  }

  handleSubmit(event) {
    // Get value of input field
    let value = this.input.current.value;
    console.log('value in input field: ' + value );
    event.preventDefault();
    // Validate 'value' and submit using your own api or something
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" ref={this.input} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

ReactDOM.render(
  <NameForm />,
  document.getElementById('root')
);

Solution 6 - Javascript

You can also write a little wrapper function like this

const onEnter = (event, callback) => event.key === 'Enter' && callback()

Then consume it on your inputs

<input 
    type="text" 
    placeholder="Title of todo" 
    onChange={e => setName(e.target.value)}
    onKeyPress={e => onEnter(e, addItem)}/>

Solution 7 - Javascript

Example of preventing Enter from submitting a form on an input, in my case it was a google maps location autocomplete input

<input
  ref={addressInputRef}
  type="text"
  name="event[location]"
  className="w-full"
  defaultValue={location}
  onChange={(value) => setLocation(value)}
  onKeyDown={(e) => {
    if (e.code === "Enter") {
      e.preventDefault()
    }
  }}
/>

Solution 8 - Javascript

const [value, setValue] = useState("");

const handleOnChange = (e) => {
    setValue(e.target.value);
};

const handleSubmit = (e) => {
    e.preventDefault();
    addTodoItem(value.trim());
    setValue("");
};

return (
    <form onSubmit={handleSubmit}>
        <input value={value} onChange={handleOnChange}></input>
    </form>
);

Solution 9 - Javascript

Here is a common use case using class-based components: The parent component provides a callback function, the child component renders the input box, and when the user presses Enter, we pass the user's input to the parent.

class ParentComponent extends React.Component {
  processInput(value) {
    alert('Parent got the input: '+value);
  }

  render() {
    return (
      <div>
        <ChildComponent handleInput={(value) => this.processInput(value)} />
      </div>
    )
  }
}

class ChildComponent extends React.Component {
  constructor(props) {
    super(props);
    this.handleKeyDown = this.handleKeyDown.bind(this);
  }

  handleKeyDown(e) {
    if (e.key === 'Enter') {
      this.props.handleInput(e.target.value);
    }
  }

  render() {
    return (
      <div>
        <input onKeyDown={this.handleKeyDown} />
      </div>
    )
  }      
}

Solution 10 - Javascript

I prefer onKeyUp since it only fires when the key is released. onKeyDown, on the other hand, will fire multiple times if for some reason the user presses and holds the key. For example, when listening for "pressing" the Enter key to make a network request, you don't want that to fire multiple times since it can be expensive.

// handler could be passed as a prop
<input type="text" onKeyUp={handleKeyPress} />

handleKeyPress(e) {
if (e.key === 'Enter') {
  // do whatever
}

}

Also, stay away from keyCode since it will be deprecated some time.

Solution 11 - Javascript

//You can use onkeyup directly on input field

    const inputField = document.querySelector("input");
        inputField.addEventListener("keyup", e => {
         
            if (e.key == "Enter") {
                 console.log("hello");
            }
        });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBill LumbertView Question on Stackoverflow
Solution 1 - JavascriptwuctView Answer on Stackoverflow
Solution 2 - JavascriptAdmirView Answer on Stackoverflow
Solution 3 - JavascriptLucaView Answer on Stackoverflow
Solution 4 - Javascriptonmyway133View Answer on Stackoverflow
Solution 5 - Javascriptc-chavezView Answer on Stackoverflow
Solution 6 - JavascriptDavid AlshView Answer on Stackoverflow
Solution 7 - JavascriptDorianView Answer on Stackoverflow
Solution 8 - Javascriptseñor SRView Answer on Stackoverflow
Solution 9 - JavascriptkruboView Answer on Stackoverflow
Solution 10 - JavascriptkawerewagabaView Answer on Stackoverflow
Solution 11 - JavascriptOmarsSaadeView Answer on Stackoverflow