dumbmatter dumbmatter - 2 months ago 28
Javascript Question

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?

Answer

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/