0

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.

asked Jan 21, 2013 at 18:43
1
  • Hmm a type of button should not submit. What browser is this? You can try changing your code to: submitDNC(); return false; Commented Jan 21, 2013 at 18:47

4 Answers 4

2

Expanding on Praveen's answer here, I'm going to write the JavaScript "unobtrusively" to further separate function, presentation, and content:

HTML

<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" />
 <button type='submit'>Add Number to Do Not Call list"</button>
</form>

(X)HTML5

Assuming that you want a 10-digit number in the box (numeric characters only), we can also use the pattern attribute on the <input> element in HTML5 as a form of validation for newer browsers (Firefox, Chrome, IE10, Opera):

<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" pattern="[0-9]{10}" />
 <button type='submit'>Add Number to Do Not Call list"</button>
</form>

JavaScript (place inside <script> tags somewhere on the page)

function submitDNC(event) {
 var valid = false;
 alert('Hello world');
 // your validation logic goes here, sets valid to TRUE if it's valid
 if(!valid) {
 event.preventDefault();
 }
}
document.getElementById('addDNCform').addEventListener( 'submit', submitDNC, false );

No need to do any synthetic button clicking if all you're trying to do is validate upon form submission. Pretty soon with HTML5 we might not even need JavaScript for this, depending on what your validation logic is.

answered Jan 21, 2013 at 18:58
Sign up to request clarification or add additional context in comments.

6 Comments

+1 for your explanation! :)
rink, it's still being submitted. Is it because I have some server-side code? But doesn't that execute when the page is loaded? I posted all the code (not updated with your function) in [jsFiddle] (jsfiddle.net/LTckU)
@Amarundo The server side code that is on the page should be executed before the page is sent to the browser. Try implementing my function and see if that works.
I'm not sure, it's working for me: jsfiddle.net/5mMmZ Have you checked Firebug/IE Developer Tools/Chrome Developer to see if any error comes up?
I did, but, it's my first time doing that, and I'm not sure what to look for. Using chrome.
|
0

In your submitDNC() function, give a return false;.

function submitDNC()
{
 alert("Hello World!");
 return false;
}

Another thing is, change your input type from button to submit. Use:

<input id="btnVldt" type="submit"
 value="Add Number to Do Not Call list" onclick="return submitDNC();" />

Explanation

The return value of an event handler determines whether or not the default browser behaviour should take place as well. In the case of clicking on links, this would be following the link, but the difference is most noticeable in form submit handlers, where you can cancel a form submission if the user has made a mistake entering the information.


Another Option

As Rink says, return false; is overkill for something that can and should be handled by preventDefault(). So, you can do this way, by using unobtrusive JavaScript.

function submitDNC()
{
 alert("Hello World!");
 var e = window.event;
 e.preventDefault();
}
answered Jan 21, 2013 at 18:46

10 Comments

Your solution works, but return false; is overkill for something that can and should be handled by preventDefault() (i.e. preventing the default action of submitting the form): stackoverflow.com/questions/1357118/…
Wouldn't you need: onclick="return submitDNC()"
@MikeChristensen Just missed. Updated. Thanks.
@rink.attendant.6 Can you check if my answer is right, am not sure about it. If possible, can you correct it?
Thanks, now I know where to type preventDefault()
|
0

To prevent submit when pressing ENTER, use this piece of code:

function checkEnter(e){
 e = e || event;
 var txtArea = /textarea/i.test((e.target || e.srcElement).tagName);
 return txtArea || (e.keyCode || e.which || e.charCode || 0) !== 13;
}

then, add the handler to the form:

document.querySelector('form').onkeypress = checkEnter;
answered Jan 21, 2013 at 18:52

Comments

0

I would change the to a Submit, although this isn't what's getting you in trouble here. For some odd reason browser programmers thought it was a good idea to code so that browsers assume buttons within forms submit them. You'll want to change onkeypress to call a function. In that function do something like this:

function keyPressPhone() {
 if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
 document.getElementById("addDNCform").submit();
 return true;
 }
 else {
 return false; // somehow prevents the form from being submitted
 }
}
answered Jan 21, 2013 at 18:53

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.