Javascript onsubmit causing page to refresh - javascript

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).

Related

Behavior of html form onsubmit event in JSFiddle

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.

How to update/change HTML content with JavaScript and prevent the page from refreshing?

I'm a newbie to scripting. I want to update HTML content with JavaScript, but as you can see
the web page keeps refreshing.
How can I prevent the page from refreshing?
Javascript:
function showResult(form) {
var coba=form.willbeshown.value;
var coba2=coba+2;
document.getElementById("showresulthere").innerHTML=coba2;
}
HTML
<form>
<input type="text" name="willbeshown" value="">
<button onclick="showResult(this.form)">Ganti1</button>
</form>
<p id="showresulthere">Result will be shown here</p>
</body>
Don’t use a form at all. You are not submitting any form data to a server. To process data in the browser, you don’t need a form. Using a form just complicates things (though such issues could be fixed by using type=button in the button element, to prevent it from acting as a submit button).
<input type="text" id="willbeshown" value="">
<button onclick=
"showResult(document.getElementById('willbeshown'))">Ganti1</button>
<p id="showresulthere">Result will be shown here</p>
<script>
function showResult(elem) {
document.getElementById("showresulthere").innerHTML = Number(elem.value) + 2;
}
</script>
I have used conversion to numeric, Number(), as I suppose you want to add 2 to the field value numerically, e.g. 42 + 2 making 44 and not as a string, 42 + 2 making 422 (which is what happens by default if you just use an input element’s value and add something to it.
Your button should be
<button onclick="showResult(this.form); return false;">Ganti1</button>
Javascript
function showResult(form) {
var coba=form.willbeshown.value;
var coba2=coba+2;
document.getElementById("showresulthere").innerHTML=coba2;
return false; // prevent form submission with page load
}
DEMO
The others will explain how you should use jQuery, but this would explain why it didn't work in your original code.
The <button> tag submits the form, so you have to add this inside your form tag to prevent form submission:
<form onsubmit="return false">
Btw, even without giving your form an explicit action, it uses the current page to submit; it's easy to think that it will not do anything without an action.
If you define a <button /> without defining its type it will work like a submit button. Just add type="button" to your button markup and the form won't be submitted.
<button type="button" onclick="showResult(this.form)">Ganti1</button>
With this change you won't need any return false or .preventDefault() "workarounds"

Javascript function prints .innerHTML but HTML only appears for a moment before vanishing

I've got a button that calls a javascript function named "submit()". In that function I simply write document.getElementById('try').innerHTML="it worked"; to test out whether or not my button is passing data to the function or not.
The problem is "it worked" gets printed for about a half second before disappearing.
I made an entire form that printed processed data to the webpage perfectly using the same html page. The only difference is that I changed the structure of my form and moved my functions to a .js file.
Although now, even if I comment out the submit() function in the .js file and paste the function within the core html file the same thing happens. I can paste is above or below the form and the same thing results.
Here is my HTML:
<div class="formsection">
<button type="Submit" onclick="Submit()">Submit</button>
</div>
</form>
</div>
<div id="output">
<p> Try this: <span id="try"></span></p>
</div>
Here is my javascript function:
<script type="text/javascript">
function Submit(){
document.getElementById("try").innerHTML="It worked";
}
</script>
you are using submit button to test your code, it executes the JS code and submitted the form.
If you don't want the form to be submit use return false in submit()
<script type="text/javascript">
function Submit(){
document.getElementById("try").innerHTML="It worked";
return false;
}
</script>
and in html again use return
<button type="Submit" onclick="return Submit()">Submit</button>
In javascript when any event handler returns false that halts the event execution.
The issue you're experiencing is due to your markup, mainly this piece:
<button type="Submit" onclick="Submit()">Submit</button>
You've specified that the button should perform a form submission when clicked, hence the javascript fires, changes the text and the page is reloaded (post back occured).
To get around that, you implement one of the following changes:
Change your markup to just be a button that fires javascript:
<input type="button" onclick="Submit()">Submit</input>
Add a statement in your javascript that cancels the default action for your submit button:
event.preventDefault(); MDN Link
Your form is submitted, that's why you see "It worked" only for a second (if at all).
Your function isn't prevents form submission.
You can use onsubmit attribute of form to specify function which will be called before form is submitted and can decide whenever it allowed or not by returning Boolean value
Your form actually gets submitted:)
Use this:
<button type="Submit" onclick="Submit(); return false;">Submit</button>
I don't see the FORM tag but if you do something like:
<form action="javascript:" onsubmit="Submit()">
Your function Submit will be called, and nothing more.
The nice thing about using a input type="submit" is your user can submit a form by hitting Enter and don't have to manage it yourself.

IE8 is submitting the form to the current page

It's working in all other browsers, and it was working on IE8 before, but I did some code cleanup and moved some things around, and now its submitting this form to it's self. It's an "ajax" uploader (yes, not really ajax, but you know what I mean)
Here is the JS:
function file_upload($theform,item_id){
$theform.attr('ACTION','io.cfm?action=updateitemfile&item_id='+item_id);
if($theform.find('[type=file]').val().length > 0){
$('iframe').one('load',function(){
$livepreview.agenda({
action:'get',
id:item_id,
type:'item',
callback:function(json){
$theform.siblings('.upload_output').append('<li style="display:none" class="file-upload"><a target="blank" href="io.cfm?action=getitemfile&item_file_id='+json[0].files.slice(-1)[0].item_file_id+'">'+json[0].files.slice(-1)[0].file_name+'</a> <a style="color:red" title="Delete file?" href="#deletefile-'+json[0].files.slice(-1)[0].item_file_id+'">[X]</a></li>').children('li').fadeIn();
$theform.siblings('.upload_output').find('.nofiles').remove();
}
});
//Resets the file input. The only way to get it cross browser compatible as resetting the val to nothing
//Doesn't work in IE8. It ignores val('') to reset it.
$theform.append('<input type="reset" style="display:none">').children('[type=reset]').click().remove();
});
}
else{
$.alert('No file selected');
return false;
}
}
/* FILE UPLOAD EVENTS */
//When they select "upload" in the modal
$('.agenda-modal .file_upload').live('submit',function(event){de
file_upload($('.agenda-modal .file_upload'),$('.agenda-modal').attr('data-defaultitemid'));
});
If you didn't know, ACTION has to be capitalized for Firefox to work. Also, i know for sure it's submitting to it's self because the iframe shows the current page inside of it's self and all the scripts get loaded again. Also, in the .live(), adding return false; does nothing.
Here is the HTML just in case:
<label>Add Attachment</label>
<form class="file_upload" method="post" enctype="multipart/form-data" target="upload_target" action="">
<input name="binary" id="file" size="27" type="file" /><br />
<br><input type="submit" name="action" value="Upload" /><br />
<iframe class="upload_target" name="upload_target" src="" style="display:none"></iframe>
</form>
<label>Attachments</label>
<ul class="upload_output">
<li class="nofiles">(No Files Added, Yet)</li>
</ul>
It is supposed to send the form to itself.
Consider that the button is of type submit (ie submits form automatically) and that the form action is empty (ie, send it self).
However, as you've correctly done, a submit handler may cause the form to not submit at all (to which I ask, what was the point of submitting in the first place? But that's past the point)
Anyway, you should stop event propagation and return false in your event handler.
You should return false; at the end of your "submit" handler.
ah - well that's hard to understand. OK well where exactly is this <iframe> defined? edit — oh duhh I see it.
edit again — OK I realize I'm sort-of jumping up and down on thin ice with my credibility here, but I suggest adding an "id" attribute to the <iframe> (with "upload_target" as the id value). Every once in a while I figure out exactly which one of "name" and "id" is important (and when/why), but that information only lasts an hour or so before my brain perversely dismisses it. (By "important" I mean specifically with <iframe> elements.)

Form not submitting with JS

I have the worlds most simple javascript function:
fnSubmit()
{
window.print();
document.formname.submit();
}
Which is called by:
<button type="button" id="submit" onclick="fnSubmit()">Submit</button>
All is well and good, the print dialog shows up, however after printing or canceling the print I get the following error:
"document.formname.submit is not a function"
My form is defined as follows: (obviously I am not using formname in the actual code but you get the idea)
<form name="formname" id="formname" method="post" action="<?=$_SERVER['SCRIPT_NAME']?>">
Obviously I am not trying to do anything special here and I have used similar approaches in the past, what in the world am I missing here?
In short: change the id of your submit button to something different than "submit". Also, don't set the name to this value either.
Now, some deeper insight. The general case is that document.formname.submit is a method that, when called, will submit the form. However, in your example, document.formname.submit is not a method anymore, but the DOM node representing the button.
This happens because elements of a form are available as attributes of its DOM node, via their name and id attributes. This wording is a bit confusing, so here comes an example:
<form name="example" id="example" action="/">
<input type="text" name="exampleField" />
<button type="button" name="submit" onclick="document.example.submit(); return false;">Submit</button>
</form>
On this example, document.forms.example.exampleField is a DOM node representing the field with name "exampleField". You can use JS to access its properties such as its value: document.forms.example.exampleField.value.
However, on this example there is an element of the form called "submit", and this is the submit button, which can be accessed with document.forms.example.submit. This overwrites the previous value, which was the function that allows you to submit the form.
EDIT:
If renaming the field isn't good for you, there is another solution. Shortly before writing this, I left the question on the site and got a response in the form of a neat JavaScript hack:
function hack() {
var form = document.createElement("form");
var myForm = document.example;
form.submit.apply(myForm);
}
See How to reliably submit an HTML form with JavaScript? for complete details
Given that your form has both an id and a name defined, you could use either one of these:
With the form tag's id:
document.getElementById('formname').submit();
With the form tag's name attribute:
document.forms['formname'].submit();
Try this:
fnSubmit()
{
window.print();
document.getElementById("formname").submit();
}
The most likely culprit is IE confusing JavaScript variables, ids, and names. Search in your source for something sharing the name of your form.
Place a input button inside your form.
Give tabindex="-1" on it.
Make It invisible using style="display:none;".
Like This
<input type="submit" tabindex="-1" style="display:none;" />

Categories