JS Submit Form


HTML page usually uses a submit button to submit a form to a handling file such as a php script. All input values of the form will be transferred to the handling file by "post" method.

<form name=sp action="formtest.php" method="post">
	Name:
	<input name="n" type="text" style="width:260px;height:22px;font-size:20px">
	<input style="font-size:15px;height:26px;" type=submit value="Submit"/>
</form>
/*****formtest.php*****/
<?php
if (isset($_POST['n']) && $_POST['n'] != "")
{
	echo "Name is: " . $_POST['n'];
}
else
	echo "Nothing there.";
?>


Name:

There is a button, its type is submit, and the form is handled by "formtest.php" via "post" method.


Sometimes javascript is used to check the input values before submitting to the handling file. This can be done by adding an onsubmit() event to the form. Following example shows how to check the input value do not contains number before submit.

<script language="javascript">
function checkform()
{
	var v=document.sf.sfn.value;
	for (var i = 0; i < v.length; i++)
	{
		if ((v.substring(i,i+1) >= 0 && v.substring(i, i+1) <= 9))
		{
			alert("Error! Name contains number.");
			return false;
		}
	}
	return true;
}
</script>
<form name=sf action="formcheck.php" method="post" onsubmit="return checkform();">
	Name:
	<input name="n" type="text" style="width:260px;height:22px;font-size:20px">
	<input style="font-size:15px;height:26px;" type=submit value="Submit"/>
</form>
/*****formcheck.php*****/
<?php
	if (isset($_POST['sfn']) && $_POST['sfn'] != "")
	{
		echo "Name is: " . $_POST['sfn'];
	}
	else
		echo "Nothing there.";
?>


Name:


javascript can also be used for form submit, by adding an onclick() event to the submit button:

<script language="javascript">
function submitform()
{
	document.forms["sp2"].submit();
}
</script>
<form name=sp2 action="formtest2.php" method="post">
	Name:
	<input name="n2" type="text" style="width:260px;font-size:22px">
	<input style="font-size: 17px" type=button onClick="submitform()" value="Submit"/>
</form>
/*****formtest2.php*****/
<?php
	if (isset($_POST['n2']) && $_POST['n2'] != "")
	{
		echo "Name is: " . $_POST['n2'];
	}
	else
		echo "Nothing there.";
?>

Name:


We can use javascript to submit the form using href instead of submit button:

<form name=sp3 action="formtest3.php" method="post">
	Name:
	<input name="n" type="text"
	style="width:260px;font-size:22px">
	<a href="javascript:document.forms['sp3'].submit()">
	<u>Submit</u></a>
	<a href="javascript:document.forms['sp3'].reset()">
	<u>Reset</u></a>
</form>
/*****formtest3.php*****/
<?php
if (isset($_POST['n3']) && $_POST['n3'] != "")
{
	echo "Name is: " . $_POST['n3'];
}
else
	echo "Nothing there.";
?>

Name: Submit Reset



Javascript can also be used for form and input box validations, please click here for details.
endmemo.com © 2024  | Terms of Use | Privacy | Home