form value is empty - javascript

I am making a UI and below is my basic getting input from forms, but it won't display the value of secondLetter if I do it like
const form = document.querySelector('#form');
let firstLetter = document.querySelector('#firstLetter').value;
let secondLetter = document.querySelector('#secondLetter').value;
const output = document.querySelector('#check');
form.addEventListener('submit', function(e){
e.preventDefault();
console.log(secondLetter);
})
But If do it like
const form = document.querySelector('#form');
let firstLetter = document.querySelector('#firstLetter').value;
let secondLetter = document.querySelector('#secondLetter');
const output = document.querySelector('#check');
form.addEventListener('submit', function(e){
e.preventDefault();
console.log(form.secondLetter.value);
})
I get the value. I don't understand what I am doing wrong or why second example work and not first. Following is my HTML for reproducing purpose
<form id="form">
<label for="firstLetter">First Letter</label>
<input type="text" id="firstLetter">
<label for="secondLetter">Second Letter</label>
<input type="text" id="secondLetter">
<input type="submit" id="check">
</form>

Your 1st code runs when the page loads (your form laod):
let secondLetter = document.querySelector('#secondLetter').value;
so secondLetter will be set to value "" , even when your form will be submited the varable is already set so you will get "".
AT the 2nd code: you set secondLetter to the element reference, and only on submit you give the value to secondLetter, not before the submit.

<input type="text" id="secondLetter"> doesn't have a value attribute, so document.querySelector('#secondLetter').value is going to be an empty string.
(If you wanted to type something into the input and then read the value, then your JS would need to wait until something had been typed … you would normally use an Event Listener for that).

Related

Insert Username and Email ID into a list/array and display it using HTML and Javascriot

I'm trying to create a function such that, when the form is submitted the details filled by the user (ie his/her name and email id) is appended to a list/array. And then the list/array is displayed.
For example...
When I fill in the credentials for the first time:
Name - A
Email - something#abc.com
The output on submitting the form should be:
[["A", "something#abc.com"]]
When I fill in the credentials for the second time:
Name - B
Email - someone#xyz.com
The output on submitting the form should be:
[["A", "something#abc.com"], ["B", "someone#xyz.com"]]
But when I tried this, I am not getting the output of the list/array.
Here's what I tried...
const info = [];
function display(){
var nm = document.getElementById("nm").value;
var em = document.getElementById("em").value;
var data = [nm, em];
info.push(data);
var text = document.createElement("h2");
text.innerHTML = info;
}
<body>
<script src="script.js"></script>
<form onsubmit="return(display())">
<input type="text" placeholder="Name" id="nm">
<input type="email" placeholder="Email" id="em">
<input type="submit" value="Submit">
</form>
</body>
The reason it's not displaying the data is for two reasons.
Everytime you submit the form, it refreshes the page. To prevent this you have to prevent the default action of the button submission. Which can be done using the function preventDefault() via an event. Better explained in the code.
You have not appended the created element to anything element, so it is not displaying anywhere on the webpage.
Both can be resolved by checking the code and it's explanation below!
const info = [];
function display(e){ // the `e` parameter is the event passed in.
e.preventDefault(); // We run the function preventDefault to prevent the page from reloading.
var nm = document.getElementById("nm").value;
var em = document.getElementById("em").value;
var data = [nm, em];
info.push(data);
var text = document.createElement("h2");
text.innerHTML = info;
document.body.appendChild(text); // You haven't appended the information to
// anything, here I append the created Element to the Body so it displays, but do note, that this displays
// the full list, you may want to change this to display only the newer data
// or perhaps append to a element that prints out each time a new user is added.
//console.log(info); You can see that the array now updateds in the console.
}
<script src="script.js"></script>
<!-- Pass the event of submitting a form as an argument -->
<form onsubmit="display(event)">
<input type="text" placeholder="Name" id="nm">
<input type="email" placeholder="Email" id="em">
<input type="submit" value="Submit">
</form>

How to alter the attributes of a form's fields without clearing the field values?

So I have this html form:
<form action="">
<input type="text" name="form-0-product_name" id="id-form-0-product_name">
<input type="text" name="form-0-product_price" id="id-form-0-product_price">
<button>Change form</button>
</form>
Please note the name and id attributes and how they contain "form-0". For a reason that doesn't really matter too much, I want the user to be able to click the "Change form" button and have all the instances of "form-0" change to "form-1". I came up with this javascript function that does that:
let button = document.querySelector("button");
let form = document.querySelector("form");
button.addEventListener("click", e => {
e.preventDefault();
const replacedForm = "form-0";
form.innerHTML = form.innerHTML.replaceAll(replacedForm, "form-1");
})
This does the trick of replacing the "form-0" strings with "form-1" ; however, it seems as though this completely resets the form. In other words, if the client has already typed some data into the text fields and then presses the change form button, the fields are cleared of their values. What I want to know is if there's a really efficient way to change the form's fields' attributes (mainly id and name) without clearing the values of the fields if their are values in them. Thanks and please let me know if I need to clarify.
You'll have to iterate over the elements and attributes individually.
let button = document.querySelector("button");
let form = document.querySelector("form");
button.addEventListener("click", e => {
e.preventDefault();
const replacedForm = "form-0";
// Select all elements with a name or id
for (const elm of form.querySelectorAll('[name], [id]')) {
for (const attrib of ['name', 'id']) {
elm[attrib] = elm[attrib].replaceAll(replacedForm, "form-1");
}
}
})
<form action="">
<input type="text" name="form-0-product_name" id="id-form-0-product_name">
<input type="text" name="form-0-product_price" id="id-form-0-product_price">
<button>Change form</button>
</form>
But this is a really strange thing to want to do in most cases. IDs in particular should not be dynamic. Strongly consider if there's an alternative way to approach the problem you're trying to solve.
You can also iterate over form.elements and modify the attribute's value property
const form = document.querySelector('form');
Array.from(form.elements).forEach(el => {
Array.from(el.attributes).forEach(att => {
att.value = att.value.replaceAll('form-0', 'form-1')
console.log(att.value)
});
})
<form action="">
<input type="text" name="form-0-product_name" id="id-form-0-product_name">
<input type="text" name="form-0-product_price" id="id-form-0-product_price">
<button>Change form</button>
</form>

Why isn't my localStorage.setItem() and localStorage.getItem() storing a value?

I want to store a user input value using localStorage then use that value in my countdown timer.
Here is the HTML where the user inputs their data:
<form action='/' method= 'GET' id='settings'>
<label> Work Time </label>
<input class='settingInput' type='number' id='workInput'>
<label id='short-break'> Short Break </label>
<input class='settingInput' id='shortBreak'>
<label id='long-break'> Long Break </label>
<input class='settingInput' id='longBreak'>
<button id = 'set-values'>Submit</button>
</form>
this is the javascript to store and retrieve the data:
var workInputValue = document.getElementById('workInput').value;
var workTimeSerialized = JSON.stringify(document.getElementById('workInput').value);
var workTimeFinal = JSON.parse(localStorage.getItem('workTimeKey'));
submitButton.addEventListener('click', (e) => {
localStorage.setItem('workTimeKey', workTimeSerialized);
console.log('submit pressed');
e.preventDefault();
})
Here is the codepen for the whole project: https://codepen.io/Games247/pen/XWJqebG
This is my first time using setItem and getItem so I may be overlooking something obvious.
Currently it looks like a pair of brackets is stored in the localStorage where workTimeKey should be.
Your linked code on codepen has a problem, in fact the code posted here corrects said problem.
var workTimeSerialized = JSON.stringify(document.getElementById('workInput'));
The above is your codepen, the problem is you are trying to serialize the HTML element to JSON rather than it's value hence the '{}' you see in your session storage.
You need to ensure it's the value of the input element and not the element itself you serialize. Like i mentioned, your code posted here resolves the issue ;
var workTimeSerialized = JSON.stringify(document.getElementById('workInput').value);
Note: Whenever you see '[]' or '{}' in session storage rather than your intended value, you are either passing an object directly or an element in your case.
Edit:
'you are most likely not either'
Your input values should be read in the submit click handler otherwise, you get the value of the input before sumbit and not after
So your code:
var workInputValue = document.getElementById('workInput').value;
var workTimeSerialized = JSON.stringify(document.getElementById('workInput').value);
var workTimeFinal = JSON.parse(localStorage.getItem('workTimeKey'));
submitButton.addEventListener('click', (e) => {
localStorage.setItem('workTimeKey', workTimeSerialized);
console.log('submit pressed');
e.preventDefault();
})
becomes:
submitButton.addEventListener('click', (e) => {
var workInputValue = document.getElementById('workInput').value;
var workTimeSerialized = JSON.stringify(document.getElementById('workInput').value);
var workTimeFinal = JSON.parse(localStorage.getItem('workTimeKey'));
localStorage.setItem('workTimeKey', workTimeSerialized);
console.log('submit pressed');
e.preventDefault();
})

Pass variable value from form javascript

Say I got a HTML form like below and want to pass the values in the textfields to JS variables.
<form name="testform" action="" method="?"
<input type="text" name="testfield1"/>
<input type="text" name="testfield2"/>
</form>
I've only passed values to variables in PHP before. When doing it in javascript, do I need a method? And the main question, how is it done?
Here are a couple of examples:
Javascript:
document.getElementById('name_of_input_control_id').value;
jQuery:
$("#name_of_input_control_id").val();
Basically you are extracting the value of the input control out of the DOM using Javascript/jQuery.
the answers are all correct but you may face problems if you dont put your code into a document.ready function ... if your codeblock is above the html part you will not find any input field with the id, because in this moment it doesnt exist...
document.addEventListener('DOMContentLoaded', function() {
var input = document.getElementById('name_of_input_control_id').value;
}, false);
jQuery
jQuery(document).ready(function($){
var input = $("#name_of_input_control_id").val();
});
You don't really need a method or an action attribute if you're simply using the text fields in Javascript
Add a submit button and an onsubmit handler to the form like this,
<form name="testform" onsubmit="return processForm(this)">
<input type="text" name="testfield1"/>
<input type="text" name="testfield2"/>
<input type="submit"/>
</form>
Then in your Javascript you could have this processForm function
function processForm(form) {
var inputs = form.getElementsByTagName("input");
// parse text field values into an object
var textValues = {};
for(var x = 0; x < inputs.length; x++) {
if(inputs[x].type != "text") {
// ignore anything which is NOT a text field
continue;
}
textValues[inputs[x].name] = inputs[x].value;
}
// textValues['testfield1'] contains value of first input
// textValues['testfield2'] contains value of second input
return false; // this causes form to NOT 'refresh' the page
}
Try the following in your "submit":
var input = $("#testfield1").val();

Expanding HTML forms using Javascript

I have a simple HTML form that asks a user to input their name, SKU, quantity, and comments. This is for a simple inventory request system.
<html>
<body>
<form id="myForm" method="post">
<input type="submit">
<br>Name: <input type="text" name="form[name]">
<br>SKU: <input type="text" name="form[SKU1]">
<br>Quantity: <input type="text" name="form[quantity1]">
<br>Comment: <input type="text" name="form[comment1]">
</form>
Add item
<script>
var num = 2; //The first option to be added is number 2
function addOption() {
var theForm = document.getElementById("myForm");
var newOption = document.createElement("input");
newOption.name = "form[SKU"+num+"]"; // form[varX]
newOption.type = "text";
theForm.appendChild(newOption); //How can I add a newline here?
optionNumber++;
}
</script>
</body>
</html>
Currently I can only get it working where it will add a single form value. I would like to recreate the entire myForm except for the name field with a single click.
Your post is very old, so presumably you've found an answer by now. However, there are some things amiss with your code.
In the JavaScript code you have
var num = 2;
This is the number that is incremented to keep track of how many "line-items" you will have on the form. In the function addOption(), though, instead of incrementing num you have
optionNumber++;
You never use optionNumber anywhere else. Your code works once, when you add the first item, but since you increment the wrong variable, you are effectively always adding option 2.
Oh, and adding the newline: you need to append a <br> element.

Categories

Resources