Amarundo
Amarundo

Reputation: 2397

Why is my HTML form being submitted?

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:

Added this:

Actually, if I use submit instead of button, it doesn't work also when clicking. However, in jsFiddle it seems to work.

Upvotes: 0

Views: 168

Answers (4)

rink.attendant.6
rink.attendant.6

Reputation: 46208

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.

Upvotes: 2

MaKR
MaKR

Reputation: 1892

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
  }
}

Upvotes: 0

lante
lante

Reputation: 7336

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;

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

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();
}

Upvotes: 0

Related Questions