i have wrote a function to activate onsubmit"" in the form.
In the function(JavaScript) i try to fill variables with input from the fieldset.
On troubleshooting i immediately found out that all the input gets cleared before i can save them into the variables.
I know that this is not how forms are used but i do like how it points out the fields that still needs to be filled.
so is there a way or someone how figured out a way to outsmart the submit to do something(function) before the refresh? or is there absolutely no way?
function objectfill() {
var vnaam = document.getElementById('Voornaam').value;
var anaam = document.getElementById('naam').value;
var mail = document.getElementById('email').value;
var tele = document.getElementById('mobiel').value;
var rknr = document.getElementById('rijksregister').value;
var actie = document.getElementById('workshop').value
var k = document.getElementsByName('Room');
var room
for (var i = 0; i < k.length; i++) {
if (k[i].checked) {
room = k[i].value;
}
}
var personeel = new personeelgegevens(pnr, vnaam, anaam, mail, tele, rknr,
actie, room);
console.log(personeel)
This was the function i used onsubmit="objectfill()"
I wanted to fill the object but obviously not working.
You just need to prevent that submit from happening so that your JavaScript can run, by calling event.preventDefault(). Also, try using element.addEventListener() instead of inline event properties.
// Assuming a form that looks like
<form id="myform">
// Do
const form = document.getElementById('form')
form.addEventListener('submit', event => {
// prevent the form from submitting
event.preventDefault()
// The rest of your form code here
})
Related
I have this function:
function selectCheckedAnswer(){
var checkbox_checked = document.querySelectorAll('input[id="check"]:checked');
var form = document.getElementById('formtosubmit');
for (let i = 0; i < checkbox_checked.length; i++) {
let item = checkbox_checked[i];
form.appendChild(item);
}
}
It is not working as expected. When debugging, there are generated one form to each checkbox checked. (because I inserted the form inside of the For loop, I know)
When I debug the code above, 2 forms are being sent to the controller
image here
...but I just get 1 of the forms and 1 checked checkbox:
image here
What I need is to send only one form with the checkboxes selected to the controller.
I think you are looking for this:
var checkbox_checked = document.querySelectorAll('input[id="check"]:checked');
var form = document.getElementById('formtosubmit');
checkbox_checked.forEach(element => {
form.innerHTML += element.innerHTML;
});
I'm using DOM to generate a form like this
const my_form = document.createElement("form");
my_form.enctype = "multipart/form-data";
my_form.onsubmit = function(){return false;};
// inputs here
const div_submit = document.createElement("div");
div_submit.className = "form-group";
const submit = document.createElement("input");
submit.type = "submit";
submit.value = "Register";
submit.onclick = function(){my_function(this.form);};
div_submit.appendChild(submit);
my_form.appendChild(div_submit);
but my problem is when I set the onClick attribute of the submit input. Using this.form works when I'm writing directly on html, but when I use JS DOM it says that this.form is not defined. How can I get the data from the other inputs and pass it as a parameter of the onCLick function?
You already have the form element by my_form.
and you can get the form inputs by
my_form.elements
which will get all form inputs.
You can loop through and get it's values.
[my_form.elements].forEach(input => console.log(input.value))
For more resources.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/elements
How can you make the browser remember what the user typed in the form, which has not yet been submitted and make the page refreshing not affect the data entered?
I have a form in which the user enters a number. Initially the form has 0 by default. I am storing the data in localStorage, so the browser can remember the data. However, when the page is refreshed, the user-entered data disappears and 0 is displayed by default. (still the localStorage data exists for it)
I tried to use jQuery's
$(".formClassName").val(localStorage.getItem(key));
but it does not work. Can anyone give me a piece of advice on this?Thank you in advance.
Edited: My form looks like this:
<form>
<!--There are multiple forms, and the only difference among them is the "name" attribute -->
Enter a number <input type="text" value="0" class"dataEntered" name="****">
<!--The button below saves the data entered in the above form -->
<input type="button" class="savedata" value="Save Value" name="****">
</form>
And I am adding the data to localStorage like below:
//JavaScript
<script>
//Using on because the website retrieves the above form dynamically
$(document).on("click", ".saveData", function(e){
//retrieve the number entered in the form
var userNum = $(this).siblings(".dataEntered").val();
//retrieve the value in name attribute
var thisFormName = $(this).attr("name");
//store the data
localStorage.setItem(thisFormName, userNum);
//Now that the save button has been pressed (not submitted to the
//server yet), and the data is stored in localStorage, I want to
//the page to show the number in userNum even after you refresh the page
//but this does not work.
$(".dataEntered").val(localStorage.setItem(thisFormName));
});
</script>
use cookie:
function addCookie(sName,sValue,day) {
var expireDate = new Date();
expireDate.setDate(expireDate.getDate()+day);
document.cookie = escape(sName) + '=' + escape(sValue) +';expires=' + expireDate.toGMTString();
}
function getCookies() {
var showAllCookie = '';
if(!document.cookie == ''){
var arrCookie = document.cookie.split('; ');
var arrLength = arrCookie.length;
var targetcookie ={};
for(var i=0; i<arrLength; i++) {
targetcookie[unescape(arrCookie[i].split('=')[0])]= unescape(arrCookie[i].split('=')[1]);
}
return targetcookie;
}
addCookie('type','1',1024);
var cookiesample = getCookies();
$(".formClassName").val(cookiesample.type);
cookiesample.type could be remembered unless the cookie is deleted.
Checkout this codepen I have it shows a functional solution to the problem. Also you need to make sure jQuery script checks if the DOM is ready, you can do that by using $(function() { }) a short hand for .ready().
$(function() {
var input = $("[type=text]");
var thisFormName = input.attr("name");
if (localStorage.getItem(thisFormName)) {
var value = parseInt(localStorage.getItem(thisFormName));
input.val(value);
}
$(document).on("click", ".savedata", function(e) {
var userNum = input.val();
localStorage.setItem(thisFormName, userNum);
input.val(localStorage.getItem(thisFormName));
});
});
I'm trying to do html form without action. It must:
1) Remember input data as normal form do.
2) Doesn't reload page
I tried:
<form action="javascript:void(0);" id="simple-form">
But on
$('#simple-form').submit();
form didn't remember input data.
Normal form
<form action="#" id="simple-form">
reloads page but also remembers input data.
Does exist another way to remember data without forms with javascript?
Update #1:
event.preventDefault(); // onsubmit event prevert
Doesn't work same because it's preventing not only reload of page but also saving of data (autocomplete).
With javascript
var form = document.getElementById("simple-form")
form.onsubmit = function (event) { event.preventDefault() }
if(localStorage){
var textfield = document.getElementById("yourTextfield");
var data = localStorage.getItem("yourTextfield");
if(data){
textfield.value = JSON.parse(data);
}
textfield.onkeydown = function(){
localStorage.setItem("yourTextfield",JSON.stringify(textfield.value));
}
}
ok alternative solution with history object
var data = history.state.textfieldName;
if(data){
textfield.value = data;
}
textfield.onkeydown = function(){
history.state.textfieldName = textfield.value;
}
Im trying to set the action of a form with javascript!
How come it wont work on this code: (what happens is that the page gets submitted to itself, as in 'action="#"'
function validateForm() {
var nr_of_pics=document.getElementById("annonsera_nr_pics").value;
var name = document.getElementById("annonsera_name");
var tel = document.getElementById("annonsera_tel");
var email = document.getElementById("annonsera_email");
var area = document.getElementById("annonsera_area");
var community = document.getElementById("annonsera_area_community");
var category = document.getElementById("annonsera_category");
var subcats = document.getElementById("annonsera_subcats").getElementsByTagName("select");
var headline = document.getElementById("annonsera_headline");
var description = document.getElementById("annonsera_des");
var price = document.getElementById("annonsera_price");
if (nameValid(name) && telValid(tel) && emailValid(email) && areaValid(area) && communityValid(community) && categoryValid(category) && subcatsValid(subcats) && headlineValid(headline) && descriptionValid(description) && priceValid(price)){
var form = document.getElementById("annonsera").action;
form = "bincgi/verify_"+category+".php";
alert (form);
return true;
}
return false;
}
and the form:
<form name="annonsera" id="annonsera" method="post" enctype="multipart/form-data" onSubmit="return validateForm();">
BY the way, the alert box wont show up either!
ALSO, setting the form action manually in HTML works fine, and the form is validated properly!
var form = document.getElementById("annonsera").action;
form = "bincgi/verify_"+category+".php";
These lines aren't doing what you seem the think they're doing.
The first line is creating a variable called 'form', and copying the form's current action into that variable as a string. The second line then sets the variable to a new value, but the form's action isn't being changed because the variable only contained a copy of the form's action.
This would be what you're after:
var formElement = document.getElementById("annonsera");
formElement.action = "bincgi/verify_"+category+".php";
However, I don't know why your alert box isn't showing up at all. Are you certain that all the validity methods are actually being passed?
Try this:
document.getElementById("annonsera").action = "bincgi/verify_"+category+".php";
The problem with your code is that you first read the action attribute into a variable:
var form = document.getElementById("annonsera").action;
and then you set the form variable to a new string but this won't update the value of the DOM element.
Give it simple like
document.annonsera.action = "bincgi/verify_"+category+".php"
and to Submit the form
document.annonsera.submit()