I have this form with 1 field. I want that when the user clicks
or hits enter
it should call a JavaScript function that will do validation and either display an error message or submit the form.
However, when hitting enter
it submits the form regardless. (So far in my JavaScript validation function I only have alert ("Hello World")
)
<form action="add-another-number-to-dnc.cshtml" method="post" id="addDNCform">
<h4>Enter 10-digit phone number without dashes, dots or parenthesis</h4>
<input type="text" name="pn" required placeholder="phone number"
title="Phone Number to Add to Do-Not-Call List"
onkeypress="if (event.keyCode == 13) document.getElementById('btnVldt').click()"/> <!-- all this is to treat [Enter] as a click -->
<input id="btnVldt" type="button" value="Add Number to Do Not Call list" onclick="submitDNC()"/>
</form>
I added all the page code in jsFiddle where you can test and verify that:
- when clicking on the button, it correctly doesn't submit the form
- when hitting
enter
it gives you an Error 404 which must mean, it's trying to load the page.
Added this:
Actually, if I use submit
instead of button
, it doesn't work also when clicking. However, in jsFiddle
it seems to work.