I have a form with a couple of inputs. I want to show the value of the inputs (including the names of the fields) in console in json format when I click the submit button.
How can I do this? I read about new FormData way, but I don't really understand how to use it (so far I've come up with this code, but it doesn't work)
//popup is my form
popup.addEventListener("submit", function (event) {
let formData = new FormData(popup);
console.log(formData);
event.preventDefault();
}, false);
If you want to get all of your data in your form (including names), and you ain't planning to use jQuery, you can try to handle the inputs by yourself based on the form:
const form = document.myForm;
form.addEventListener("submit", function(event) {
event.preventDefault(); // Always preventDefault() first
let formData = new FormData(this);
let object = {};
formData.forEach((value, key) => {
object[key] = value
});
let json = JSON.stringify(object);
console.log(json);
}, false);
<form name="myForm">
<input name="input1">
<input name="input2">
<input name="input3">
<button>Submit</button>
</form>
Related
I know that you can easily get data from a form like:
function getData(event) {
event.preventDefault();
const inpt = document.getElementById("inpt").value;
return inpt;
}
//OR
function getData(event) {
event.preventDefault();
const inpt = document.getElementById('form').elements[0].value;
return inpt;
}
<form id="form" onsubmit="getData(event)">
<input id="inpt" type="text"></input>
</form>
what I'd like to know is if this same value could be reached through the event property or a this keyword, withou using a "getElementBy..." of any sort or any querySelector.
I think I like James' answer better. Much simpler. Haven't tested either too extensively sorry.
If you assign all of your form elements a name attribute, on the form submission event you can use the FormData Api to get their data. I believe this won't work on I.E. or other older browsers (check for browser compatibility).
Form Data: https://developer.mozilla.org/en-US/docs/Web/API/FormData#browser_compatibility
Object.fromEntries(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries#browser_compatibility
<form id="form" onsubmit="getData()">
<input name="input1" id="inpt" type="text"></input>
<input name="input2" id="NotNeededForThis" type="text"></input>
</form>
function getData(event) {
event.preventDefault();
const formData = new FormData(event.target);
const formObject = Object.fromEntries(data.entries());
return formObject;
}
This will return the object:
{
input1: "whatever the value was",
input2: "whatever the value was"
}
Since the event listener is set on the form, the form element is available as
event.target
And so the text field value would be accessible by
event.target.elements[0].value
The form element is also this within the submit handler, so you could also do
this.elements[0].value.
You can access the value of the input through the event directly. For example in the function to access the data of the input field with the name 'input1':
function getData(event){
//format event.target.nameOfInput.value
//for the input field with the name input1
let inp1 = event.target.input1.value;
//for the input field with the name input2
let inp2 = event.target.input2.value;
//
console.log( inp1 , inp2)
}
I am trying to get the value of a textarea that I have append into a fieldset of my form.
To do so, when I submit my form, the following code is triggered:
function handleSubmit(e) {
e.preventDefault();
console.log(document.getElementById('Observation_1').value);
const data = new FormData(e.target);
const value = data.get('Observation_1');
console.log(value);
}
const form = document.querySelector('form');
form.addEventListener('submit', handleSubmit);
<form>
<textarea id="Observation_1"></textarea><br>
<button type="submit">Test</button>
</form>
however, my console.log (value); returns me null, while my console.log(document.getElementById('Observation_1').value);
return me the content of my textarea.
Can someone explain me why i have a null return and help me to fix my code so i can get the actual content of my textarea please.
You probably don't have a name="Observation_1" attribute on the textarea.
I'm (very) new to web development and am working on learning back-end currently.
I am trying to figure out how to use multiple inputs inside a form, but am struggling to get the actual input, instead of the element itself using this code to create the form:
<form id="newPostForm">
<input name="titleInput" placeholder="title"><br>
<input name="bodyInput" placeholder="body">
<button>Submit</button>
</form>
and this JS to try and output the user input to the console:
const newPost = document.getElementById("newPostForm")
const title = document.querySelector(".titleInput")
const body = document.querySelector(".bodyInput")
newPost.addEventListener("submit", (e) => {
e.preventDefault()
console.log(title, Body)
})
When I hit the submit button the console displays null null. This is probably a super simple question, but I'd appreciate any help.
After fixing the case issue with your body variable, you need to get the value of the inputs by accessing their value property. Then you want to move those variables into your submit handler, otherwise you're only getting the value once, when the page loads, and they're blank:
const newPost = document.getElementById("newPostForm");
newPost.addEventListener("submit", (e) => {
const title = document.querySelector(".titleInput").value;
const body = document.querySelector(".bodyInput").value;
e.preventDefault()
console.log(title, body)
})
<form id="newPostForm">
<input name="titleInput" class="titleInput" placeholder="title"><br>
<input name="bodyInput" class="bodyInput" placeholder="body">
<button>Submit</button>
</form>
I have this form:
<form action="#" id="form-add">
<input type="text" name="test[]" value="hello">
<input type="text" name="test[]" value="bye">
<button type="submit"><Submit/button>
</form>
And I want, when the user submits, this information to be sent via AJAX using FormData like this:
$('form-add').submit(function (event)
{
//Prevents from submitting form
event.preventDefault();
var formData = new FormData();
var form_fields = $('#form-add').serializeArray();
$.each(form_fields, function (key, input)
{
formData.append(input.name, input.value);
});
});
The problem is when I try to check the entries inside the variable formData, it only shows the value of the first input:
console.log(formData.get('teste[]'));
//Returns
hello
How can I send this kind of inputs using FormData?
It will send all values. But if you want to check on a client you'll need to use getAll method.
const form = new FormData
form.append('a', 1)
form.append('a', 2)
console.log(form.getAll('a'))
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;
}