Multiple Submit Buttons on HTML Form - Designate One Button as Default

Multiple submit buttons on HTML form – designate one button as default

My suggestion is don't fight this behaviour. You can effectively alter the order using floats. For example:

<p id="buttons">
<input type="submit" name="next" value="Next">
<input type="submit" name="prev" value="Previous">
</p>

with:

#buttons { overflow: hidden; }
#buttons input { float: right; }

will effectively reverse the order and thus the "Next" button will be the value triggered by hitting enter.

This kind of technique will cover many circumstances without having to resort to more hacky JavaScript methods.

Enter key action when multiple submit buttons exist on a single form

After doing some more research I realized I asked the wrong question. However, it's not letting me delete the question, so I'm posting the answer to my actual question here.

My question should have been, "When multiple inputs exist in a single form, how does the browser determine which one is chosen when hitting the enter key?"

The answer is, when the enter key is hit, the first input of type="submit" is chosen. However, IE will skip any submit buttons that are hidden with display:none.

I found the answer here:

Multiple submit buttons on HTML form – designate one button as default

My fix was to set the submit button to position: absolute; left: -1000% rather than display:none. I got that solution from @bobince on the linked answer, however, left:-100% did not push it completely off the page for me so I changed it to left:-1000%.

Two submit buttons in one form

If you give each one a name, the clicked one will be sent through as any other input.

<input type="submit" name="button_1" value="Click me">

Multiple submit buttons in an HTML form

I'm just doing the trick of floating the buttons to the right.

This way the Prev button is left of the Next button, but the Next comes first in the HTML structure:

.f {
float: right;
}
.clr {
clear: both;
}
<form action="action" method="get">
<input type="text" name="abc">
<div id="buttons">
<input type="submit" class="f" name="next" value="Next">
<input type="submit" class="f" name="prev" value="Prev">
<div class="clr"></div><!-- This div prevents later elements from floating with the buttons. Keeps them 'inside' div#buttons -->
</div>
</form>

Pressing Return in a HTML-Form with multiple Submit-Buttons

You could, theoretically at least, have three submit buttons in your form.

Button two is the existing 'less-important' button (from halfway down the form), button three is the existing 'actual-submit' button from your existing form.

Button one should be hidden (using CSS display:none or visibility: hidden) and should perform exactly the same function as your current 'actual-submit.' I think it'll still be the first button to be found by the browser, regardless of its visibility.

<form method="post" method="whatever.php" enctype="form/multipart">

<fieldset id="first">

<label>...<input />
<label>...<input />
<label>...<input />

<input type="submit" value="submit" style="visibility: hidden;" <!-- or "display: none" --> />
<input class="less_important" type="submit" value="submit" />

</fieldset>

<fieldset id="second">

<label>...<input />
<label>...<input />
<label>...<input />

<input type="submit" value="submit" class="actual_submit" />

</fieldset>

</form>

Edited in response to comments:

I thought hidden buttons were also disabled by default? [md5sum]

A valid point, but I made the mistake of testing only in Firefox (3.5.7, Ubuntu 9.10) before posting, in which the technique worked1, for both. The complete xhtml file is pasted (below) that forms the basis of my testing subsequently to these comments.

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<title>3button form</title>
<link rel="stylesheet" type="text/css" href="css/stylesheet.css" />
<script type="text/javascript" src="js/jquery.js"></script>

<script type="text/javascript">

$(document).ready(

function() {

$('input[type="submit"]').click(
function(e){
alert("button " + $(this).attr("name"));
}
);

}
);
</script>

</head>

<body>

<form method="post" method="whatever.php" enctype="form/multipart">

<fieldset id="first">

<label>...<input />
<label>...<input />
<label>...<input />

<input name="one" type="submit" value="submit" style="display:none;" /><!-- or "display: none" -->
<input name="two" class="less_important" type="submit" value="submit" />

</fieldset>

<fieldset id="second">

<label>...<input />
<label>...<input />
<label>...<input />

<input name="three" type="submit" value="submit" class="actual_submit" />

</fieldset>

</form>

</body>

</html>

display: none should prevent a button from being an active part of the form (included in the result set, and eligible for default-button-ness); visibility: hidden should not. However both of these cases are got wrong by some browsers. The normal way to have an invisible first submit button is to position: absolute; it and move it way off the page (eg. with left: -4000px). This is ugly but reliable. It's also a good idea to change its tabindex so it doesn't interfere in the expected form tabbing order.

There are, at least, two points I have to raise to this comment. In order:

  1. "The normal way..." I was unaware that there was a normal way, and presented this option as a possibility to achieve an aim, in the full knowledge that there were/are almost certainly any number of better ways, particularly given that I don't see a good reason for multiple submit buttons on the same form.
  2. Given the latter sentence of the above point, I'd like to make it clear that I don't advocate doing this. At all. It feels like an ugly, and non-semantic, hack to have more than one submit button, with -in the OP's instance- one button apparently not being a submit button.
  3. The notion of `position: absolute; left: -4000px;` had occurred to me, but it seemed to effect much the same as `visibility: hidden;`, and I have an innate dislike of `position: absolute;` for whatever reason...so I went with the option that was less objectionable to me at the time of writing... =)

I appreciate your comment about the tabindex, though, that was something that I never gave any thought to, at all.

I'm sorry if I sound somewhat snippy, it's late, I'm tired...yadda-yadda; I've been testing in various browsers since my return home and it seems that Firefox 3.5+ gives the same behaviour -reporting 'button one' on both Windows XP and Ubuntu 9.10, all Webkit browsers (Midori, Epiphany, Safari and Chrome) fail and report 'button two.'

So it's definitely a fail-worthy idea to display: none; the submit button. Whereas the visibility:hidden at least works.



  1. By which I mean that hitting 'enter' triggered the form-submit event, or the click event of the first submit button of the form, regardless of whether that first submit was `display: none;` or `visibility: hidden`.

    Please be aware that my jQuery skills are limited, so the tests employed (I ran only at a time to try and prevent conflicts occurring in execution, commenting out the one I didn't run at that time, both are presented -one, clearly, commented out) may well be insufficient and non-representative.

How is the default submit button on an HTML form determined?

If you submit the form via JavaScript (i.e., formElement.submit() or anything equivalent), then none of the submit buttons are considered successful and none of their values are included in the submitted data. (Note that if you submit the form by using submitElement.click() then the submit that you had a reference to is considered active; this doesn't really fall under the remit of your question since here the submit button is unambiguous but I thought I'd include it for people who read the first part and wonder how to make a submit button successful via JavaScript form submission. Of course, the form's onsubmit handlers will still fire this way whereas they wouldn't via form.submit() so that's another kettle of fish...)

If the form is submitted by hitting Enter while in a non-textarea field, then it's actually down to the user agent to decide what it wants here. The specifications don't say anything about submitting a form using the Enter key while in a text entry field (if you tab to a button and activate it using space or whatever, then there's no problem as that specific submit button is unambiguously used). All it says is that a form must be submitted when a submit button is activated. It's not even a requirement that hitting Enter in e.g. a text input will submit the form.

I believe that Internet Explorer chooses the submit button that appears first in the source; I have a feeling that Firefox and Opera choose the button with the lowest tabindex, falling back to the first defined if nothing else is defined. There's also some complications regarding whether the submits have a non-default value attribute IIRC.

The point to take away is that there is no defined standard for what happens here and it's entirely at the whim of the browser - so as far as possible in whatever you're doing, try to avoid relying on any particular behaviour. If you really must know, you can probably find out the behaviour of the various browser versions, but when I investigated this a while back there were some quite convoluted conditions (which of course are subject to change with new browser versions) and I'd advise you to avoid it if possible!

reactjs form: with two submit buttons doing two different tasks for same form

Use a React ref on the form element to access the form fields in the submit handlers and attach the submit handlers to each button's onClick handler.

function Formtwosubmits() {
const formRef = useRef(); // (1) <-- React ref for form DOMNode

function handlesubmit_task1(event) {
event.preventDefault();
const { value } = formRef.current.myInput; // (4) <-- access form inputs by name

// ...anything you need to do with form fields
console.log("handler 1", value);

formRef.current.reset(); // (5) <-- reset form if necessary
}

function handlesubmit_task2(event) {
event.preventDefault();
const { value } = formRef.current.myInput;

console.log("handler 2", value);

formRef.current.reset();
}

return (
<>
<form ref={formRef}> // (2) <-- Attach ref to element
<button
variant="contained"
color="primary"
type="submit"
onClick={handlesubmit_task1} // (3) <-- Attach submit handler 1
>
task 1
</button>
<button
variant="contained"
color="primary"
type="submit"
onClick={handlesubmit_task2} // (3) <-- Attach submit handler 2
>
task 2
</button>
.... here input fields
<input name="myInput" type="text" />
</form>
</>
);
}

Demo

Edit reactjs-form-with-two-submit-buttons-doing-two-different-tasks-for-same-form

Update

You can assign an id to each submit button and access the React Synthetic event's nativeEvent to get to the underlying browser event and access the submitter value.

Create a submitHandler to receive the form's onSubmit event and check the submitter value and proxy the onSubmit event to the proper handler based on id.

const handlers = {
submit1: handlesubmit_task1,
submit2: handlesubmit_task2,
}

const submitHandler = (e) => {
const { id } = e.nativeEvent.submitter; // <-- access submitter id
handlers[id](e); // <--proxy event to proper callback handler
};

function handlesubmit_task1(event) {
event.preventDefault();
const { value } = event.target.myInput;
console.log("handler 1", value);
event.target.reset();
}

function handlesubmit_task2(event) {
event.preventDefault();
const { value } = event.target.myInput;
console.log("handler 2", value);
event.target.reset();
}

<form onSubmit={submitHandler}>
<button
id="submit1" // <-- id 1
variant="contained"
color="primary"
type="submit"
>
task 1
</button>
<button
id="submit2" // <-- id 2
variant="contained"
color="primary"
type="submit"
>
task 2
</button>
.... here input fields
<input name="myInput" type="text" />
</form>

Edit reactjs-form-with-two-submit-buttons-doing-two-different-tasks-for-same-form (forked)

How to have multiple submit buttons for a quiz on one page

Your markAnswers function is looping through all inputs, that's why you're getting the answers for all of them when you click any of the buttons.

You can fix this by changing the id of the forms to be like formId1, formId2 etc., then giving that id to the markAnswers function.

Example:

function markAnswers(id) {
$(`#q${id}`).each(function () {\
if ($.inArray(this.value, answers[this.id]) === -1) {
$(this).parent().append(`<br>The correct answer: ${answers[this.id]}`);
} else {
$(this).parent().append("<br><font style='color:green;'>Correct!</font>");
}
});
}

$("form").on("submit", function (e) {
e.preventDefault();
const id = e.target.id.replace("formId", "")
markAnswers(id);
});

Additionally, you can disable the button in the same submit event as well:

$("form").on("submit", function (e) {
...

$(`#submitId${id}`).each(function () {
this.setAttribute('disabled', true);
this.value = "Check answers"
})

});

Here's a working example: Codesandbox



Related Topics



Leave a reply



Submit