KOMPX.COM or COMPMISCELLANEA.COM   

JavaScript form submit

Submitting a form using JavaScript. A dropdown list (form + select + multiple options) is processed without any submit button. Example:

HTML code:


<form action="action.php" method="post">
	<select name="page" required="required" onchange="this.form.submit()">
		<option value="" selected="selected" disabled="disabled">Select a page</option>
		<option value="os/dos.htm">DOS</option>
		<option value="os/linux.htm">Linux</option>
		<option value="os/windows.htm">Windows</option>
	</select>
	<noscript><input type="submit" value="Submit" /></noscript>
</form>

When an option has been chosen from the dropdown list, the form's state is changed. So the onchange event occurs and JavaScript code in onchange is executed: the process of the form submission in started by the script, not by clicking submit button which is absent.

Some server-side script is meant then to handle the form action. The script is supposed to get what the form sends and have it processed. A PHP script in action.php is used in the example.

PHP code:


<?php
if (isset($_POST["page"])) {
	header("Location: $_POST[page]");
	exit;
} else {
	echo "No options selected";
}

$_POST is an array of variables passed to the current script via the HTTP POST method. So $_POST[page] contains the content of the value attribute in a select option. That is, a URL. It is passed from form to PHP script and the script redirects browser to the URL / page selected.

HTML code of <noscript><input type="submit" value="Submit" /></noscript> is present in the form as a fallback in case JavaScript happens to be turned off. Then there is a submit button to appear and the form is usable anyway.

Browser support
Windows
Internet Explorer 4.01+
Firefox 1.0+
Google Chrome
Opera 3.0+
Safari 3.1+
SeaMonkey 1.0+
Mozilla 0.6+
Netscape 3.04+
Linux
Firefox 1.0+
Google Chrome / Chromium
Opera 5.0+
SeaMonkey 1.0+
Mozilla 0.6+
Netscape 3.04+
More