How to validate a form while using a multiple submit button

As we have seen already about Javascript Form validation, let us now see how to validate a form while using multiple submit button. Usually a form has a single submit button but sometimes it might need more than one submit buttons and the form is validated to check whether which button is pressed. Its merely easy to validate the form when there is a single submit button.

But it’s quiet tricky to perform validation on form with multiple submit button.

The below form has different value with same name for submit button.

1.Add the multiple submit buttons in a form:

<html>
<head></head>
<body>
<form action="" method="POST" id="form" name="form">
<input type="text" name="textbox" id="textbox" value=""/>
<input align="middle" type="submit" value="Quotes" name="Submit" id="button"/>
<input align="middle" type="submit" value="Blog" name="Submit" id="button"/>
</form>
</body>
</html>

2. Now add the action for the buttons

<html>
<head>
<script type="text/javascript">
function submitForm(target)
{
    if (target == 0){ document.form.action="http://TheQuotes.Net"; document.form.submit();}
    if (target == 1){ document.form.action="http://qualitypoint.blogspot.in";  document.form.submit();}
}
</script>
</head>
<body>
<form action="" method="POST" id="form" name="form">
<input type="text" name="textbox" id="textbox" value=""/>
<input align="middle" type="submit" value="Quotes" name="Submit" id="button" onClick="return submitForm(0)"/>
<input align="middle" type="submit" value="Blog" name="Submit" id="button" onClick="return submitForm(1)"/>
</form>
</body>
</html>

3. In the above code validation has not performed for textbox to perform the validation just do the following

<html>
<head>
<script type="text/javascript">
function submitForm(target)
{
    if(document.getElementById('textbox').value=="")
	{
		alert("Text box should contains some value");
		document.getElementById('textbox').focus();
		return false;
	}
    if (target == 0){ document.form.action="http://TheQuotes.Net"; document.form.submit();}
    if (target == 1){ document.form.action="http://qualitypoint.blogspot.in";  document.form.submit();}
}
</script>
</head>
<body>
<form action="" method="POST" id="form" name="form">
<input type="text" name="textbox" id="textbox" value=""/>
<input align="middle" type="submit" value="Quotes" name="Submit" id="button" onClick="return submitForm(0)"/>
<input align="middle" type="submit" value="Blog" name="Submit" id="button" onClick="return submitForm(1)"/>
</form>
</body>
</html>

If you know any other simple solution you can post it here

Posted in Html, Javascript Tagged with: ,