Why is my HTML form being submitted? - javascript

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.

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.

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

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;

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

Related

Calculations with JavaScript without submitting the form [duplicate]

In the following page, with Firefox the remove button submits the form, but the add button does not.
How do I prevent the remove button from submitting the form?
function addItem() {
var v = $('form :hidden:last').attr('name');
var n = /(.*)input/.exec(v);
var newPrefix;
if (n[1].length == 0) {
newPrefix = '1';
} else {
newPrefix = parseInt(n[1]) + 1;
}
var oldElem = $('form tr:last');
var newElem = oldElem.clone(true);
var lastHidden = $('form :hidden:last');
lastHidden.val(newPrefix);
var pat = '=\"' + n[1] + 'input';
newElem.html(newElem.html().replace(new RegExp(pat, 'g'), '=\"' + newPrefix + 'input'));
newElem.appendTo('table');
$('form :hidden:last').val('');
}
function removeItem() {
var rows = $('form tr');
if (rows.length > 2) {
rows[rows.length - 1].html('');
$('form :hidden:last').val('');
} else {
alert('Cannot remove any more rows');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<html>
<body>
<form autocomplete="off" method="post" action="">
<p>Title:<input type="text" /></p>
<button onclick="addItem(); return false;">Add Item</button>
<button onclick="removeItem(); return false;">Remove Last Item</button>
<table>
<th>Name</th>
<tr>
<td><input type="text" id="input1" name="input1" /></td>
<td><input type="hidden" id="input2" name="input2" /></td>
</tr>
</table>
<input id="submit" type="submit" name="submit" value="Submit">
</form>
</body>
</html>
You're using an HTML5 button element. Remember the reason is this button has a default behavior of submit, as stated in the W3 specification as seen here:
W3C HTML5 Button
So you need to specify its type explicitly:
<button type="button">Button</button>
in order to override the default submit type. I just want to point out the reason why this happens.
Set the type on your buttons:
<button type="button" onclick="addItem(); return false;">Add Item</button>
<button type="button" onclick="removeItem(); return false;">Remove Last Item</button>
...that'll keep them from triggering a submit action when an exception occurs in the event handler. Then, fix your removeItem() function so that it doesn't trigger an exception:
function removeItem() {
var rows = $('form tr');
if ( rows.length > 2 ) {
// change: work on filtered jQuery object
rows.filter(":last").html('');
$('form :hidden:last').val('');
} else {
alert('Cannot remove any more rows');
}
}
Note the change: your original code extracted a HTML element from the jQuery set, and then tried to call a jQuery method on it - this threw an exception, resulting in the default behavior for the button.
FWIW, there's another way you could go with this... Wire up your event handlers using jQuery, and use the preventDefault() method on jQuery's event object to cancel the default behavior up-front:
$(function() // execute once the DOM has loaded
{
// wire up Add Item button click event
$("#AddItem").click(function(event)
{
event.preventDefault(); // cancel default behavior
//... rest of add logic
});
// wire up Remove Last Item button click event
$("RemoveLastItem").click(function(event)
{
event.preventDefault(); // cancel default behavior
//... rest of remove last logic
});
});
...
<button type="button" id="AddItem" name="AddItem">Add Item</button>
<button type="button" id="RemoveLastItem" name="RemoveLastItem">Remove Last Item</button>
This technique keeps all of your logic in one place, making it easier to debug... it also allows you to implement a fall-back by changing the type on the buttons back to submit and handling the event server-side - this is known as unobtrusive JavaScript.
Sometime ago I needed something very similar... and I got it.
So what I put here is how I do the tricks to have a form able to be submitted by JavaScript without any validating and execute validation only when the user presses a button (typically a send button).
For the example I will use a minimal form, only with two fields and a submit button.
Remember what is wanted:
From JavaScript it must be able to be submitted without any checking. However, if the user presses such a button, the validation must be done and form sent only if pass the validation.
Normally all would start from something near this (I removed all extra stuff not important):
<form method="post" id="theFormID" name="theFormID" action="">
<input type="text" id="Field1" name="Field1" />
<input type="text" id="Field2" name="Field2" />
<input type="submit" value="Send" onclick="JavaScript:return Validator();" />
</form>
See how form tag has no onsubmit="..." (remember it was a condition not to have it).
The problem is that the form is always submitted, no matter if onclick returns true or false.
If I change type="submit" for type="button", it seems to work but does not. It never sends the form, but that can be done easily.
So finally I used this:
<form method="post" id="theFormID" name="theFormID" action="">
<input type="text" id="Field1" name="Field1" />
<input type="text" id="Field2" name="Field2" />
<input type="button" value="Send" onclick="JavaScript:return Validator();" />
</form>
And on function Validator, where return True; is, I also add a JavaScript submit sentence, something similar to this:
function Validator(){
// ...bla bla bla... the checks
if( ){
document.getElementById('theFormID').submit();
return(true);
}else{
return(false);
}
}
The id="" is just for JavaScript getElementById, the name="" is just for it to appear on POST data.
On such way it works as I need.
I put this just for people that need no onsubmit function on the form, but make some validation when a button is press by user.
Why I need no onsubmit on form tag? Easy, on other JavaScript parts I need to perform a submit but I do not want there to be any validation.
The reason: If user is the one that performs the submit I want and need the validation to be done, but if it is JavaScript sometimes I need to perform the submit while such validations would avoid it.
It may sounds strange, but not when thinking for example: on a Login ... with some restrictions... like not allow to be used PHP sessions and neither cookies are allowed!
So any link must be converted to such form submit, so the login data is not lost.
When no login is yet done, it must also work. So no validation must be performed on links.
But I want to present a message to the user if the user has not entered both fields, user and pass. So if one is missing, the form must not be sent! there is the problem.
See the problem: the form must not be sent when one field is empty only if the user has pressed a button, if it is a JavaScript code it must be able to be sent.
If I do the work on onsubmit on the form tag, I would need to know if it is the user or other JavaScript. Since no parameters can be passed, it is not possible directly, so some people add a variable to tell if validation must be done or not. First thing on validation function is to check that variable value, etc... Too complicated and code does not say what is really wanted.
So the solution is not to have onsubmit on the form tag. Insead put it where it really is needed, on the button.
For the other side, why put onsubmit code since conceptually I do not want onsubmit validation. I really want button validation.
Not only the code is more clear, it is where it must be. Just remember this:
- I do not want JavaScript to validate the form (that must be always done by PHP on the server side)
- I want to show to the user a message telling all fields must not be empty, that needs JavaScript (client side)
So why some people (think or tell me) it must be done on an onsumbit validation? No, conceptually I am not doing a onsumbit validating at client side. I am just doing something on a button get pressed, so why not just let that to be implemented?
Well that code and style does the trick perfectly. On any JavaScript that I need to send the form I just put:
document.getElementById('theFormID').action='./GoToThisPage.php'; // Where to go
document.getElementById('theFormID').submit(); // Send POST data and go there
And that skips validation when I do not need it. It just sends the form and loads a different page, etc.
But if the user clicks the submit button (aka type="button" not type="submit") the validation is done before letting the form be submitted and if not valid not sent.
Well hope this helps others not to try long and complicated code. Just not use onsubmit if not needed, and use onclick. But just remember to change type="submit" to type="button" and please do not forget to do the submit() by JavaScript.
I agree with Shog9, though I might instead use:
<input type = "button" onClick="addItem(); return false;" value="Add Item" />
According to w3schools, the <button> tag has different behavior on different browsers.
You can simply get the reference of your buttons using jQuery, and prevent its propagation like below:
$(document).ready(function () {
$('#BUTTON_ID').click(function(e) {
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
return false;
});});
$("form").submit(function () { return false; });
that will prevent the button from submitting or you can just change the button type to "button" <input type="button"/> instead of <input type="submit"/>
Which will only work if this button isn't the only button in this form.
Suppose your HTML form has id="form_id"
<form id="form_id">
<!--your HTML code-->
</form>
Add this jQuery snippet to your code to see result,
$("#form_id").submit(function(){
return false;
});
Buttons like <button>Click to do something</button> are submit buttons.
You must add type
This is an html5 error like has been said, you can still have the button as a submit (if you want to cover both javascript and non javascript users) using it like:
<button type="submit" onclick="return false"> Register </button>
This way you will cancel the submit but still do whatever you are doing in jquery or javascript function`s and do the submit for users who dont have javascript.
Just add e.preventDefault(); in your method should prevent your page from submitting forms.
function myFunc(e){
e.preventDefault();
}
According to the MDN Web Docs
The preventDefault () method of the Event interface tells the user
agent that if the event is not explicitly processed, its default
action should not be taken into account as it would normally be. The
event continues to propagate as usual, unless one of its listeners
calls stopPropagation () or stopImmediatePropagation (), either of
which terminates the propagation.
The return false prevents the default behavior. but the return false breaks the bubbling of additional click events. This means if there are any other click bindings after this function gets called, those others do not Consider.
<button id="btnSubmit" type="button">PostData</button>
<Script> $("#btnSubmit").click(function(){
// do stuff
return false;
}); </Script>
Or simply you can put like this
<button type="submit" onclick="return false"> PostData</button>
I am sure that on FF the
removeItem
function encounter a JavaScript error, this not happend on IE
When javascript error appear the "return false" code won't run, making the page to postback
Set your button in normal way and use event.preventDefault like..
<button onclick="myFunc(e)"> Remove </button>
...
...
In function...
function myFunc(e){
e.preventDefault();
}
return false;
You can return false at the end of the function or after the function call.
Just as long as it's the last thing that happens, the form will not submit.
if you have <input />
use it
<input type="button"/>
if you have <button>btn</button>
use it
<button type="button">btn</button>
Here's a simple approach:
$('.mybutton').click(function(){
/* Perform some button action ... */
alert("I don't like it when you press my button!");
/* Then, the most important part ... */
return false;
});
I'm not able to test this right now, but I would think you could use jQuery's preventDefault method.
The following sample code show you how to prevent button click from submitting form.
You may try my sample code:
<form autocomplete="off" method="post" action="">
<p>Title:
<input type="text" />
</p>
<input type="button" onclick="addItem()" value="Add Item">
<input type="button" onclick="removeItem()" value="Remove Last Item">
<table>
<th>Name</th>
<tr>
<td>
<input type="text" id="input1" name="input1" />
</td>
<td>
<input type="hidden" id="input2" name="input2" />
</td>
</tr>
</table>
<input id="submit" type="submit" name="submit" value="Submit">
</form>
<script language="javascript">
function addItem() {
return false;
}
function removeItem() {
return false;
}
</script>
The function removeItem actually contains an error, which makes the form button do it's default behaviour (submitting the form). The javascript error console will usually give a pointer in this case.
Check out the function removeItem in the javascript part:
The line:
rows[rows.length-1].html('');
doesn't work. Try this instead:
rows.eq(rows.length-1).html('');
https://developer.mozilla.org/pt-BR/docs/Web/API/HTMLFormElement/submit_event
Do your logic on the form onsubmit event
submitter Read only
An HTMLElement object which identifies the button or other element which was invoked to trigger the form being submitted.
onsubmit="(evt) => console.log(evt)"
The event itself will bring along the caller and some usefull info.
Just use evt.preventDefault(); (default submit) evt.stopPropagation(); (submit bubbling) if the caller is a

How to detect that user has input some value in my form

I have one situation where i want detect that user has input some value or not.Let me explain :
I have one registration form where i have user name, email, phone, password this field are there. Now in that form I have two buttons "Save", "Continue".
When user click on "Save" it will fire validation. When click on "Continue" user will have a popup that "Are you sure you do not want to fill the form?" , here without validation fire i would like to user redirect to another page.
How could I overcome this issue? Is there any event that can help me to find out that user did not entered any thing in form? Or any jQuery?
Thanks
Have a manual function which tests for form fields when you press the Continue button.
function isFilled() {
if ($('#myFields1').value !== '' && $('#myField2').value !== '')
return true
else
return false
}
You can use required attribute at form elements. form will not be valid if field having required attribute without value is present. You can also use pattern attribute to specify RegExp pattern for valid input.
<form>
<input type="text" />
<input type="text" />
<input type="text" />
<input type="submit">
</form>
<script>
document.querySelector("form").onsubmit = function(e) {
e.preventDefault();
for (input of e.target.querySelectorAll("input")) {
if (input.value.length === 0) {
// redirect here
location.reload();
break;
}
}
// else submit form at complete of loop
this.submit();
}
</script>

How can I run some code when a submit fails due to an input being required?

How can I run some code when a submit fails due to an input being required and still have the alert (with "Please fill out this field") occur? Is there some sort of submit attempt event, or how do I get my submit event to run if a required input is left blank?
Desired Effect:
user submits form with an empty required input (submit event normally)
let browser alert user that required input is empty (default behavior of required attribute)
run some other logic function
Use Case: I would like to take advantage of the required attribute which scrolls to and alerts the user of a required field; however, this prevents the submit listener from running all together. I want the rest of my form logic to run.
var logicFunction = function () { alert('working'); };
var form = document.getElementById('test');
form.addEventListener('submit', function(event) {
// want to be able to run something here while still displaying the message
// "Please fill out this field" caused by the required attribute on the input element
event.preventDefault();
logicFunction();
});
<form id="test">
<input type="text" placeholder="leave this blank" required>
<input type="submit">
</form>
you would need to restructure your setup and handle "errors" manually,
when a field is required on a html level and left empty, the submit button isn't actually fired.
var form = document.getElementById('test');
form.addEventListener('submit', function(event) {
if(text01.value == '') submit.innerHTML = "That's empty";
else submit.innerHTML = "That's not empty.";
event.preventDefault();
// want to be able to run something here while still displaying the message
// "Please fill out this field" caused by the required attribute on the input element
});
<form id="test">
<input id="text01" type="text" placeholder="leave this blank">
<input type="submit">
<div id="submit"></div>
</form>

How to call the onclick function after pressing Enter

I am making a chat web application, to send a message, there's an input type="text" and an input type="button", using a function in JavaScript, I managed to work it out by adding onclick="sendMessage()" as an attribute for the input button, but I need to click on it, but I want it to work like any chat messengers or apps, the client writes something down and hits ENTER key, this could work if I used a <form onsubmit="sendMessage()"> and input type="submit" but then the page will refresh, How can I do this?
<form onsubmit="sendMessage();return false">
That prevents the default action of sending a request to the server.
This in-case you want also diable the enter button from Posting to server and execute the Js script.
<input type="text" id="txtSearch" onkeydown="if (event.keyCode == 13)
{document.getElementById('btnSearch').click(); return false;}"/>
<input type="button" id="btnSearch" value="Search" onclick="doSomething();"/>
You'll have to hook into the onkeypress/up/down events for the textbox.
This should get you started:
Enter key press event in JavaScript
Use onkeydown() (or keyPress or keyUp, depending on semantics) instead of on click - this will get you an event with the event.keyCode you want - 13 - and you can easily submit using an AJAX request (i.e. XMLHttpRequest)
Simple Code: - raw Javascript, Don't need JQuery:
<html>
<script>
function keyPress(e)
{
if (!e) e = window.event; // needed for cross browser compatibility
alert(e.keyCode); // You want 13 here , so
// if (e.keyCode == 13)
// etc..
// return true; or false, if you want to cancel event
}
</script>
<body>
<input type="text" onkeydown="keyPress()" size="20"/>xx
</body>
</html>

How do I submit a form to JavaScript without the submit button?

<form>
<input type="text" name="sometext">
<input type="button" value="Send" onClick="sendsometext(this.form);">
</form>
How would that be without using the submit button (I don't want it at all), just submitting the form by pressing the Enter key.
EDITED: I don't want to submit the form at all. I just want to type some text in the input field and call the function by the Enter key. Can I do this without JS?
<form>
<input type="text" name="sometext">
<input type="button" value="Send" onClick="this.form.submit">
</form>
Or, from the sendsometext function:
function sendsometext(form){
form.submit();
}
To run the function when the form submits (when the user presses Enter), try the following:
<form onsubmit="sendsometext(this)">
<input type="text" name="sometext">
</form>
If you return false from sendsometext, then the form will not submit.
Edit (Again)
Apparently you don't want to submit the form, all you want to do is let the function process the data and then do something with it. If your sendsometext function returns false, then the form should not submit:
function sendsometext(form){
//do something with the form;
return false;
}
and then the html code:
<form onsubmit="return sendsometext(this)">
<input type="text" name="sometext">
</form>
If this does not work, then please specify what browser you are using, and what happens. Also post a demo page with how you have implemented it. You cannot sumbmit the form to JavaScript without the use of JavaScript (that does not make sense).
Actually, I think you are looking for form.onsubmit
<form onSubmit="sendsometext(this.form);">
<input type="text" name="sometext">
<input type="submit" value="Send">
</form>
I wonder if the OP is missing the basic information that the browser automatically submits the form when you press Enter in any text field inside the form. That's why you can use the onsubmit handler if you want to invoke a method in response to the Enter key, per Marius' and Wogan's answers.
This is how you would create a Javascript function that acts on the the enter key being pressed to submit the form, instead of pressing the submit button.
Edit: On the code below where you see document.forms[0].submit() //submit the form ... You can change this line to point towards your function. That would stop the submission process and instead call your function when you press enter.
From http://jennifermadden.com/javascript/stringEnterKeyDetector.html
<input type="text" onKeyPress="checkEnter(event)">
function checkEnter(e){ //e is event object passed from function invocation
var characterCode;
if(e && e.which){ //if which property of event object is supported (NN4)
e = e
characterCode = e.which //character code is contained in NN4's which property
}
else{
e = event
characterCode = e.keyCode //character code is contained in IE's keyCode property
}
if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
document.forms[0].submit() //submit the form
return false
}
else{
return true
}
}

Categories

Resources