Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React form with multiple buttons - how to choose one to handle onSubmit event?

Let's say I have this HTML:

<div id="container"></div>

<p>Output: <span id="output"></span></p>

and this JS:

function otherAction(e) {
  document.getElementById('output').innerHTML = 'otherAction';
  e.preventDefault();
}

function submit(e) {
  document.getElementById('output').innerHTML = 'submit';
  e.preventDefault();
}

ReactDOM.render(
  <form onSubmit={submit}>
    <input type="text" defaultValue="foo" />
    <button onClick={otherAction}>Other Action</button>
    <button type="submit">Submit</button>
  </form>,
  document.getElementById('container')
);

Actually, let's not just say it, let's put it in a JSFiddle example. What I want to happen is that:

  1. Clicking the "Other Action" button triggers the otherAction function (it does!)

  2. Clicking the "Submit" button triggers the submit function (it does!)

  3. Putting your cursor in the text box and pressing enter triggers the submit function (this does not work currently!)

In #3, what happens instead is that otherAction gets triggered. How can I change that?

like image 911
dumbmatter Avatar asked Sep 17 '16 15:09

dumbmatter


People also ask

How do you select multiple buttons in React?

Multiple selection ButtonGroup supports checkbox type selection in which multiple button can be selected. This can be achieved by adding input element along with id attribute with its corresponding label along with htmlFor attribute inside the target element.

How do you handle two submit buttons in React JS?

React JS, two submit buttons in one form - Stack Overflow // You need to add a onSubmit event to the form. This will trigger when you submit the for as you do any other html form (including pressing the submit button) <form onSubmit={this.


1 Answers

If you set the first button to type="button" it should work.

<button type="button" onClick={otherAction}>Other Action</button>

https://jsfiddle.net/L0urqamz/3/

like image 78
neurotik Avatar answered Oct 02 '22 10:10

neurotik