0

I have a form that's using an anchor for a submit button like this:

<!DOCTYPE html>
<head>
    <script src="jquery.js"></script>
</head>
<body>

<form action="" method="post">
    <input type="text" pattern="[A-Za-z]{3}" />
    <a href="#" class="submit">Submit</a>
    <input type="submit" />
</form>

<script>
$(".submit").click( function(e) {
    var form = $(this).parents('form:first');
    form.submit();
    //e.preventDefault();
});
</script>

</body>
</html>

When I click the submit button, I see a message telling me that the validation failed. When I click the submit anchor, the form gets submitted. How can I trigger the validation when using an anchor as a submit button?

I can do this:

<form action="" method="post">
    <input type="text" pattern="[A-Za-z]{3}" />
    <a href="#" class="submit">Submit</a>
    <input style="display: none" id="i_submit" type="submit" />
</form>

//snip

<script>
$(".submit").click( function(e) {
    $("#i_submit").click();
});
</script>

And it does validate the form, prevents submission and draws a red border around the input field but it doesn't show any kind of error message like it does when a real submit button is clicked.

How do I get the error message to pop up as if the real submit button was clicked?

PsiX
  • 1,661
  • 1
  • 17
  • 35

2 Answers2

0

Using jQuery you can do it like this only:

<form action="" method="post" id="form1">
    <input type="text" pattern="[A-Za-z]{3}" />
    <a href="#" class="submit">Submit</a>
    <input style="display: none" id="i_submit" type="submit" />
</form>

$(".submit").click(function(e){
e.preventDefault();
if(validate()) // function that validates your form (returns true or false)
{
$("#form1").submit();
}
});
Mayank Tripathi
  • 1,346
  • 7
  • 21
-1

If you want to use the hyper link as a submit button, you could use the following format to trigger the function.

Submit

You could also go here: HTML tag <a> want to add both href and onclick working

Community
  • 1
  • 1
  • I'm not looking for a workaround that requires manual validation. I want a way to invoke the validation as if the submit button was clicked. –  Apr 27 '14 at 08:57