4

I used the form component in react-bootstrap-validation, and here are many input, checkbox and a submit button in the form.

<Form className="detail-model__form" onValidSubmit={this.handleValidSubmit}>
  <button type="button" className="btn btn-danger" onClick={this.deleteSomeValue}>delete</button>
  <button className="btn btn-primary">submit</button>
  <Table className="detail-model__form__table">
    <thead>
      <tr>
        <th style={{width:120}}>Key</th>
        <th>Value</th>
        <th style={{width:160}}>opperate</th>
      </tr>
    </thead>
    <tbody>
      {this.state.list.map( (item, i) =>
        <tr key={i}>
          <td>
            <Checkbox checked={item.checked} onChange={() = >{item.checked=!item.checked;this.forceUpdate();}}/>
          </td>
          <td>
            <ValidatedInput
                type="text"
                name={'hash_key_' + i}
                value={item.field}
                validate={(val) => {
                  if(val.length)
                    return true;
                  return "need Key";
                }}
            />
          </td>
          <td>
            <span
              className="table-btn"
              onClick={() => {
                this.state.actions.push({
                  "action": "hdel",
                  "field": item.field
                });
                this.state.list.splice(i, 1);
                this.state.length--;
                this.forceUpdate();
              }}
            >delete</span>
          </td>
        </tr>
      )}
    </tbody>
  </Table>
</Form>

Now I want prevent the submit event when the input or checkbox on focus and the enter key is pressed.

I have seen here are some solutions that can set the type of button to button instead of submit, but I need to use the onValidSubmit property to validate the data format.

I try to use the onKeyUp to log the enter key is pressed, but not effective

QAQMiao
  • 43
  • 1
  • 5

1 Answers1

3

You can also use onKeyDown event.

Associate this event to your input and write a function to call "preventDefault()" when enter was typed.

class App extends React.Component {

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

  handleSubmit(event) {
    alert('Submit');
  }

  handleKeyDown(event) {
    if (event.keyCode === 13 ) {
      event.preventDefault();
    }
  }

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <input type="text" onKeyDown={this.handleKeyDown}/> 
          <input type="submit" value="Submit" />
        </form>
      </div>  
    )
  }
}

In the codepen snippet below you can see and test this code.

https://codepen.io/alexandremucci/pen/rzpxRy

If you want to block enter for all inputs, you can also move "onKeyDown" event to tag form:

<form onSubmit={this.handleSubmit} onKeyDown={this.handleKeyDown}>