Behavior of html form onsubmit event in JSFiddle - javascript

I have a simple form which has nothing other than a submit button. All I want to do is prevent submission of the form (I know it doesn't make any sense but this is only for illustration). So I'm making use of the form's onsubmit event and this event returns false. This does work but this is where the 'incomprehensible behavior' arises.
I can associate the return false; statement with the onsubmit event of the form either by using inline JavaScript or keep it in a different place.
<form onsubmit="return false;" id="form1" method="post">
<input type="submit" id="btnButton" value="Submit" />
</form>
Now, the aforementioned code works just fine. See => http://jsfiddle.net/MccK5/
I can even modify the above code as follows in order to make the JavaScript separate (unobtrusive).
--some html markup initially
<form onsubmit="return falsifier()" id="form1" method="post">
<input type="submit" id="btnButton" value="Submit" />
</form>
<script>
function falsifier() {
return false;
}
</script>
--other html markup follows
Here, the script tag is placed right after form in the HTML markup.
This works too. See => http://jsfiddle.net/AfdQ5/
But when I shift the JavaScript to an different place (ex: external file), this doesn't seem to work.
By taking a look into the console in inspect element, I noted the error falsifier is not defined.
See this here => http://jsfiddle.net/5cR5R/2/
Could someone elaborate on why this is so?

You're encountering a design feature (or flaw) in JSFiddle:
In JSFiddle, the "JavaScript" pane is not the direct source code of a referenced JavaScript file, instead JSFiddle wraps that code as below and inserts it into <head>. Just go View Source to see what it does:
<script type='text/javascript'>
//<![CDATA[
window.onload=function(){
function falsifier() {
return false;
}
}
//]]>
</script>
Your <form> elements can't find falsifier because falsifier only exists within the scope of this anonymous function.

Related

Unable to get value of form field

I'm learning javascript and tried my hand at calling functions. Based on the example here, I tried to use the logic in my test html:
<html>
<head>
<script>
function ShowForm()
{
var field_value = document.forms["test_form"]["my_name"].value;
document.write(field_value);
}
</script>
</head>
<body>
<form action="" name="test_form" onsubmit="return ShowForm();" method="post">
<input type="text" name="my_name" placeholder="Type your name"/>
<button type="submit">My button</button>
</form>
</body>
</html>
I found that the html renders correctly, however upon clicking the "My button" button, the page simply reloads without displaying the additional html I expected.
The main different is that I'm trying to use <button> for the click/submit action. Is it possible to use a <button> and activate the javascript? Or should I just style the <input> as a button?
What am I doing wrong here?
Use
onsubmit="ShowForm();return false"
Instead of
onsubmit="return ShowForm();"
Adding return false will prevent page from reloading, removing return from return ShowForm(); will allow javascript to run return false after ShowForm().
Example

Javascript return false behavior what's the deal?

So I am loading an html page with a basic script and a basic form. However when the page loads there are two radio buttons the user can select, YES or NO. If you the user selects neither, I would like to present an alert box. I successfully present the alert box, but when the user clicks the "okay" button within the alert box the user is redirected to a different page. I added the statement, return false; in hopes that this wouldn't happen.
The code is as follows,
<!-- Javascript radiobutton form validation -->
<script type="text/javascript">
function valForm(form) {
if(!document.getElementById('splash_false').checked && !document.getElementById('splash_true').checked ) {
alert('You either like splash pages or dislike em, choose one ...please');
return false;
}
}
</script>
<!-- Javascript radiobutton form validation END -->
</head>
<body>
<img src="pics/DSCN1566-300x225.jpg" alt="" width="640" height="auto" />
<h1>Hello Javascript redirection.</h1><br />
<p>
<form name="tosplashornottosplash" action="splash-process.php" method="post">
Splash pages are stupid.
<input type="radio" name="splash" id="splash_false" value="false" /> No
<input type="radio" name="splash" id="splash_true" value="true" /> Yes
<input type="submit" name="splashSubmit" onClick="return valForm(tosplashornottosplash)" value="Enter" />
</form>
</p>
You should place your handler in the form's onsubmit callback
<form onsubmit="return valForm(this)" action="splash-process.php" method="post">
Returning false to the onsubmit handler will prevent your form from being posted
Try to make it an onsubmit-callback on the form, instead of an onclick-callback on the button. That way, returning false will stop the form from posting.
Side note:
Since you don't seem to use the reference to the form in your callback, there is no need to pass it to the callback function. So you could just as well call it like this, from the onsubmit-attribute on the form:
onsubmit="return valForm()"
And get rid of the the form variable in the callback signature:
function valForm() {
...
}
You need to bind to the form's onsubmit event:
<form onsubmit="return valForm()">
(Note that the form parameter in your valForm function was never actually used nor was it properly filled in either. The return valForm(tosplashornottosplash) referred to an non-existant tosplashornottosplash JavaScript variable and thus evaluated to undefined.)
However it's recommended that you bind your event handlers in the JavaScript code itself instead of wiring them in the HTML markup:
document.getElementById("myform").addEventListener("submit", valForm, false);
This assumes you gave your form the ID myform and that this code is executed after the form element is loaded into the DOM. You can ensure this by putting your JavaScript at the bottom of the page (just before closing body) or by binding to the DOMContentLoaded event of the document.
To support older IE browsers as well, you need to use attachEvent when addEventListener is not available. The article on addEventListener at MDN suggests something like:
if (form.addEventListener) {
form.addEventListener("submit", valForm, false);
} else if (form.attachEvent) {
form.attachEvent("onsubmit", valForm);
}
Alternatively, you can throw jQuery in which facilitates DOM selection (e.g. $("form[name=myform])") and takes care of the cross-browser compatibility issues for you (e.g. $.on('submit', valForm)).

Form disappears within ascx page

So this is as should be on jsfiddle.
But when I put it within a .ascx page. Which loads within an .aspx page. The <form> decides to make itself null.
Anyone know why it is doing this?
More specifically:
document.getElementById('emvForm').submit();
The above line is returning null.
Okay so looking at the code I noticed I am getting:
<form id="1" runat="server">
<form id="emvForm">
</form>
</form>
Firefox ignores the second form because it is a nested form. The id remains the same it hasn't changed because runat not being defined on it.
Anyway of bypassing this?
Looking at your code you can better do this:
instead of calling:
document.getElementById('emvForm').submit();
Return true:
return true;
Then modify your input button to this:
<input type="submit" value="Submit Form" id="SubmitButton" class="contactFormButton submit emailValid" onClick="return validForm();">
Now when you return true the form will be submitted and where your return false in the validForm function the forms stops the submit.

Form fields value get reset without page load

Following is my code in which i am trying to accomplish, when user clicks on the submit button then my javascript function sets all the value to null in the textfields of the form whose id='contact_form' without loading the page . Kindly let me know how can i modify the following code to accomplish the functionality i've been trying to do.
Thanks!!
<script type='text/javascript'>
$(document).ready(function(){
$('#love').click(function(e) {
document.contact_form.name.value = '';
alert('aloha!!');
//stop the form from being submitted (not working fine)
e.preventDefault();
}
}
</script>
<form name='abc' action='' id='abc' >
<input type="submit" id='love' />
</form>
I have also tried the following function it worked fine but its not preventing from the page load
<script type='text/javascript'>
function js(){
document.contact_form.name.value = '';
//stop the form from being submitted (NOT WORKING!!)
preventDefault();
}
}
</script>
If you try onsubmit="return false;" in the form tag your form will not be submitted. Unfortunately it will NEVER be submit. Unless you are not planning to submit it via AJAX you have to modify your onsubmit event like this:
<form onsubmit="return callFunction()">
function callFunction() {
if(condition)
return true;
else
return false;
}
$("#abc").submit( function() {
// do everything you want.
return false; //will prevent the reload.
});
To have a function execute when the form submits you have to do something like this;
<form onsubmit="return validate();">
your form here
</form>
Then you can have your check in a function called 'validate()' (or whatever you want to call it)
Make sure the validate() function returns true is the form is allowed to submit, or returns false if the page is not allowed to submit.
Also put id's and names on your input elements, that way you can access them much easier.
Assuming you have an HTML like this :
<form>
<input type="text" id="text" />
<input type="submit" id='submit' value="clear above field without reloading" />
</form>
And you want the text field value to clear when a user submits without reloading using jQuery, then following script will be your remedy :
$(function(){
$('#submit').click(function(){
$('#text').value('');
})
});
A form can be submitted in many ways, not only by clicking on a submit buttons. You should really watch for submit events, and cancel them with preventDefault (instead of click events that might trigger the submit). See #user1359163's answer.
But you problem seem to be document.contact_form.name.value. There is no property contact_form on the document object, so this will raise an error. The preventDefault is not executed, your form gets submitted and you never see the error. Set your debugger to "Stop on errors"!
You might want something like document.forms["contact"], but I don't know your HTML. An id selector for the input element would be the better choice.

Javascript onsubmit causing page to refresh

Really simple form
<form id="addDonor" name="addDonor" onsubmit="addDonor(); return false;" action="" method="post" enctype="multipart/form-data">
<div class="sectionHeader">Add New Donor</div>
<div class="formRow"><label>Name</label> <input class="inputText fullTextBar" type="text" name="userName">
<div class="formRow"><button style="margin-left:350px; width: 80px" type="button" class="publish">Add Donor</button></div>
</form>
And the addDonor function
<script type="text/javascript">
function addDonor(){
alert("test");
return false;
}
</script>
Eventually that function will include some jquery ajax to submit the info. But, baby, steps. Right now I can't even get the alert to show up. Also, when I hit "Enter" on my keyboard, the whole page refreshes, when I press "Add Donor" nothing happens.
I'm sure it has to be a simple problem. I think it's one of those things that I just need someone else's eyes to point out.
Try assigning the onsubmit event in javascript:
document.getElementById("addDonor").onsubmit = function () {
alert("test");
return false;
}
The problem is that your function is named addDonor and your element is addDonor. Every element with an id has an object created under document to identify it. Try alert(addDonor) in the inline onsubmit to see that it alerts an HTML element, not a function. Inline functions execute in a scope chain inside document, so addDonor points to document.addDonor before it reaches window.addDonor (your function).
you should change your <button> to an <input type="submit"> (as #fireshadow52 suggested) that should fix your problem. you should try the Wc3 Schools online javascript tester to try out simple javascripts before you put it in a page, or any other one that you prefer. google has something along these lines. also, you can normally try the javascript console on your respective browser.
Your button is explicitly set to type="button", which won't make it submit the form. Change it to <button type="submit">, or to <input type="submit"> if you prefer (I like the styling options of <button> myself).

Categories