HTML reset after form submit - javascript

today I started learning JavaScript and I want to calculate two numbers from a text field, using JavaScript. I want to display the result as HTML on the website itself. When I use a form to submit the values, it keeps resetting my modified HTML (the result section shows the actual result for a second but keeps switching back to the default value).
This does not happen when using a button. But since I want to add radio buttons to choose from a mathematical operation, I'd prefer a form (I'm also not quite sure how to determine which radio button is checked via JS).
this is my HTML-Form
<form name="calcForm" onsubmit="calc(num1.value, num2.value)">
<input type="text" id="num1">
<input type="text" id="num2">
<input type="submit" value="submit">
</form>
This is my resolution-section (which resets when using a form)
<div id="calcRes" style="display:block;">Lorem ipsum dolor sit amet</div>
The actual JavaScript function
function calc(num1, num2) {
var res = Number(num1)+Number(num2);
document.getElementById('calcRes').innerHTML = "Result is " + res;
}
As I said above, the result is being displayed when using a button instead of a 'form'
<button onclick="calc(num1.value, num2.value)">Calculate</button>
I'd like to know why the modified HTML switches back to default, a solution how to avoid this and if there's any "bad practice" in my code. I've also tried to search for this issue but I can't find anything. I guess, this is just a noobish problem but as I said, I'm a complete beginner so please be patient with me.

The form is being submitted and hence the page is being reloaded. To avoid this you need to prevent the form' submission. In your case
<form name="calcForm" onsubmit="calc(num1.value, num2.value); return false;">
should do the trick.

<form> onsubmit default functionality is to submit the form information to the server and resets the page on click of the submit button.
In the above code, on click of the form submit, the function calc is called, but it also resets the page after the function is called, which is why the modified HTML switches back to default.
This default behaviour can be prevented by using event.preventDefault() which cancels the event if it is cancelable. Adding this line to the start your calc function would prevent the default behaviour.
Refer to MDN Docs for more information about event.preventDefault()

You could simply squeeze in the line
document.getElementById("calcForm").reset();
after the line
document.getElementById('calcRes').innerHTML = "Result is " + res;
But you have to add the id="calcForm" to your <form> Tag.
The submit-Action is to understand as simply ending all the user input and do something with it. And after that, you don't need you inputs anymore so it will be deleted automatically. With the button-click, the form does not know that you are actually done with your input. its just a button-click. so it will leave the input as it is.

Related

Pre-loading text in textarea for user to edit and submit shows text briefly then blanks out. Why?

I'm writing an edit function (plain javascript & HTML / Chrome / Windows 10).
The data is in localStorage as a series of records, just 2 records in the toy code mentioned below.
I want the user to specify the number of the record to edit, then the code should pre-fill the textarea field with the retrieved content of that record. I want to allow the user to make changes and then press a Store button to store it back in localStorage.
My problem is that when I prefill the input field, I see the record content briefly and then the input field clears. I've tried .value and .defaultValue
editField.value = localStorage.getItem('jnl' + locStoreNo).replace(/(.*?) `\d*?`/, "$1");
and
editField.defaultValue = localStorage.getItem('jnl' + locStoreNo).replace(/(.*?) `\d*?`/, "$1");
the result is the same. (The regex is to hide a sequence number)
The code is in a JSFiddle here: https://jsfiddle.net/roygrubb/zxedbfqr/2/
That performs more or less the same - it shows the value briefly - but then does something different: It goes to a 404. I don't understand this either ¯_(ツ)_/¯
What I'm trying to do seems so basic, that I think I must be missing something blindingly obvious.
What have I missed? Thanks!
Whenever you've got a <form> that you want to handle through JavaScript, you have to ensure that the default form submission action does not happen. If the <form> does not have an "action" attribute, the default is to reload the current page.
By default, a <button> element will be assumed to have "submit" as its type. To prevent form submission, therefore, the simplest thing to do is make the button have "button" as its type.
That may not be all you need to do, depending on the details of the form. It may be necessary (or simply a good defensive move) to have a handler for the "submit" event on the form to prevent the default action.

Change an input value and submit the form on keypress (not just enter to send)

I'm really confused. I want to make a sort of a hotkey that changes the value of a hidden input field and submits the form. How can I do that? I've read numerous blogs and tutorials but all assume that I just want to submit the filled form after pressing enter. While I just don't understand how the very "structure" of a form acts in javascript.
Should I fill the hidden input like this:
document.getElementById('foo').value='bar'
I don't think there's even a way to see if its value was changed so I'm not sure.
And then, how do I submit the form, if I have:
<form name='myform' method='post' action='url.html'>
I tried document.myform.submit() and document.myform.form.submit(), and I've also tried giving the form an id and using document.getElementById('myformid').submit() but none of these work! I usually get the error TypeError: 'undefined' is not an object.
I'm new to javascript, I'm used to working with python but it has a completely different philosophy, and maybe that's the source of my confusion. I'd very appreciate some explanation, not just a code snippet.
Thanks!
You can always check the hidden field with the Development Tools of your Browser - just press F12 and you will see it. Go to the DOM list (within the Development Tool) and then you see the actual value of that field.
To submit a form via JavaScript normally document.name.submit() is enough. Another option is that you use e.g. jQuery to submit a form via AJAX (with the help of jQuery.serialize)
If you want to use document.getElementById('myformid').submit() you have to give an ID to your form like that :
<form name='myform' id="myform" method='post' action='url.html'>
It's the same thing about your hidden field.
document.getElementById('foo').value='bar' assume you have an hidden like that :
<input type="hidden" name="foo" id="foo" />
You can try the following approach
<form name='myform' method='post' action='url.html'>
// your fields here
// then use a input type button to have a button and define an on click event
</form>
<script type = "text/javscript">
use the event in your script
//change your hidden field value here and
// submit the form by
myform.submit();
</script>
You can use ajax or jquery as there is a function named on key up it means after pressing a key on the last field which ever you choose as you leave the key on keyboard it will submit the forms.
check this okay http://www.w3schools.com/php/php_ajax_livesearch.asp

Onclick to submit a form

There is a PHP-generated HTML 4 transitional page that is used to edit data from a database of a single record. The user has two options: to store changes or delete the record. I use a form with controls (some of them are hidden):
<form method="post" action="object_mod.php"><!-- this is another file -->
<!-- inputs follow -->
As I want to process two actions ie. delete or save a record I put two submit buttons on the form, before </FORM> tag:
<input type="submit" id="btnSubmit" value="Save">
<input type="submit" id="btnDelete" value="Delete">
</form>
Because the user should confirm deletion I added the following onclick event:
<input type="submit" id="btnDelete" value="Delete" onclick="javascript:deleteRecordConfirm();">
(I also tried without javascript: and onclick="javascript:deleteRecordConfirm(); return true;"), but it doesn't submit a form.
The JS function is
function deleteRecordConfirm(){
if(confirm('Are you sure to delete?')){
document.getElementById("field_action").value=-1;
//document.forms[0].submit();
return true;
}
}
This field_action is set to -1 so I know in object_mod.php that I want to delete record rather than save it.
Here go question, why this form doesn't submit on deletion?
I think it would be good if a user has Javascript disabled to submit a form anyway, even without confirmation so that is why I use <INPUT TYPE="submit"> for deletion. Is it a good idea? I was thinking about giving two independent forms (in fact deletion should have only one hidden field with record id) with their own submit buttons, one for deletion and the other for saving.
In fact the page will work in some kind of intranet, with users who I trust and I'm not afraid of hacking or something, but any security remarks are also welcome.
(I tested it on Firefox 19.0 and Javascript console shows no errors, w3c validator says it's a valid page).
The form should submit according to your code. The only thing I spot is that you should terminate the input tags with />.
BUT... this way, even if the the confirm is cancelled, the form will be submitted. Use the form.onsubmit handler and if that returns false, the form will not submit.
I dont think #B3aT's answer is right in that not unconditionally the best way to "externalise" so to say. Many the the simplest is the best.
I think the best way is to "externalize" the actual form posting.
//make regular buttons (not submit)
//call your own functions (save and delete)
//after you have done your logic do document.forms["myform"].submit();
Another solution is to add a checkbox named "delete" and rename the "save" button to "Done or do". And on server side, if "delete" is activated, then ..delete it.
Usually the "delete" is required "per entry" level (same user have multiple records), so you will have to make a separate button/link and eventually do an ajax request/access an URL with ?delete=1&id=3.
You need to make custom yes/no windows or use a jQuery plugin for it, the only browser standard is "confirm".
OK, it worked, and this was in fact very stupid mistake. The problem was with this button as it was outside the form. I was so sure that I have it inside that I did not review PHP code but copied all from script not the HTML output as I should have done.
As I understand this correctly the line document.forms[0].submit(); worked but it was not because it was button who submitted the form but document.form[0] object itself.
Thank you for all your answers. I will try this form.onsubmit hint from Marcell.

HTML button to submit a form elsewhere on the page

I want to have a form on the main section of my webpage with buttons along the bottom of this section to submit it.
I also want to have a side bar with links to other pages, but make it so that whenever a link is clicked it acts as a button to submit the form too. (ie in the HTML, the code for these links will be outside of the form tags, but I would like them to still act as buttons for the form)
Is this possible?
You can solve this very easy without JavaScript in HTML5:
<input type="submit" form="id_of_the_form" value="Submit">
<form id="id_of_the_form" action method></form>
And you can style those buttons as you like. As in the example, the button can be placed at any point within the dom - no need to put it into the form.
Use the following onclick handler in your link, replacing formId with the ID for the form you want to submit...
onclick="document.getElementById('formId').submit();return false;"
Update
As #Juan (and others, especially #JoeTaylor) have mentioned, the above will not fire any client-side validation code associated with the form. The easiest way that I'm aware of to make it do so is to fire the click event of a submit button within the form. For instance, this could be used on your link...
onclick="document.getElementById('formSubmitButton').click();return false;"
Although you don't mention anything to do with server-side processing, I will take the assumption that is the point of your form. One additional thing I would say on the back of this is that you should ALWAYS replicate the validation back on the server. JavaScript is very easy to bypass, and so you should make sure the values reaching your server are correct, and never assume the JavaScript has done it's job.
The easiest way to ensure your form is submitted and validated by whatever function you've attached is not to call the form's submit() method, but to call its submit button's click() method instead.
Consider the following form:
<form id="bar" method="post" action="/echo/html/">
<input type="text" id="foo" name="foo">
<input type="submit" value="Submit">
</form>
Right now, clicking submit doesn't do anything special. But what if you wanted to ensure the text input had a value before sending anything off to the server? You might accomplish that as follows:
function validateBarForm() {
var txt = this.querySelector("input[type=text]");
if (txt.value == "") {
txt.style.outline = "solid red 2px";
return false;
}
}
document.getElementById("bar").onsubmit = validateBarForm;
Now if you click submit the form won't be submitted with a blank text input. But what if you submit the form programmatically? Let's add a link first...
submit form
Note that this link is outside of the form tag. We can trivially attach a submission function:
function submitBarForm() {
document.getElementById("bar").submit();
}
document.getElementById("submit-bar").onclick = submitBarForm;
We click "submit form" and... Whoops! The validation function is not performed! There are a few ways to skirt this issue, but my favourite is to simply have JavaScript simulate a click to the submit button. I find this holds up to changes a lot better than hardcoding a call to the validation function.
function submitBarForm() {
document.querySelector("#bar input[type=submit]").click();
}
Now when you click the link, the form is validated, and if everything checks out it's submitted too. But don't take my word for it--head on over to jsfiddle.net and see for yourself.
By adding an onclick javascript function to your form.
document.forms["myform"].submit();
Where "myform" is the id of your form. Here's a nice walkthrough: http://www.javascript-coder.com/javascript-form/javascript-form-submit.phtml
For example, the button might be:
<button onclick="document.forms['myform'].submit();">Hi</button>
Yes the button's click event add document.getElementById('formId').submit();
<form name="myform" action="action.php">
// Your form
</form>
Submit form
Or you can use jQuery:
<form name="myform" action="action.php">
// Your form
</form>
Your text
I do this myself with hidden submit buttons in the actual form, and outside of the form - anywhere else on the page - labels that reference the submit button and fire it.
In the form:
<input type='submit' id='hiddenSubmit'>
And anywhere else:
<label for='hiddenSubmit'>click me!</label>
Seems to do the job.

How do you write strings to the middle of a web page?

I'm trying to have users enter info into a form (via radio buttons), manipulate the input data, and write resulting text onto the middle of a web page--beneath the radio buttoned form. So I have variables assigned to whenever a user selects a radio button, the onClick event calling a function something like:
function saveValue1(value) {
someVariable=value;<br>
}
And when users click a Submit button, a function works like it's supposed to, ultimately writing an output string. The problem is how to write the string value in the middle of the page. I have this [pseudo]code at the end of the function (pretend the string I want to write to the page is named aVariable):
document.getElementById('aPlace').innerHTML=aVariable;
And of course there's HTML in the displayed page like this:
<div id="aPlace"></div>
After a user pressed the form's Submit button the correct output variable is displayed very briefly, and then disappears. Why is this? And how should I be writing this code instead?
Thanks for helping a newbie, as always.
The form is probably submitted. put a "return false" at the end to stop it submitting the form
It seems that the browser is refreshing? How is the form data handled?
If the form is needed only to add the text to the page, I would add a button
<button onclick="saveValue1("+value+");")>
and avoid submitting the form.

Categories