Displaying the content of an input for several divs - javascript

I want to give all .firstname-show the content from the input but I don't know how to do it. Here's code:
<input type="text" id="firstname" name="firstname" placeholder="First name">
<button id="firstname-btn" onclick="show()">SHOW</button>
<div class="firstname-show"></div>
<div class="firstname-show"></div>
function show() {
var name = document.getElementById('firstname').value;
document.querySelectorAll('.firstname-show').textContent = name;
}

Query selector will return an array so you have to iterate using for loop. see below function.
function show() {
var name = document.getElementById('firstname').value;
var elements = document.querySelectorAll('.firstname-show');
for(var i in elements){
elements[i].textContent = name;
}
}
https://jsfiddle.net/kagf25c1/

Since the querySelectorAll returns a collection, you can use the forEach method on the collection to browse each element and apply the processing you want
const show = () => {
let value = document.getElementById('firstname').value;
document.querySelectorAll('.firstname-show')
.forEach(div => div.textContent = value);
}
<input type="text" id="firstname" name="firstname" placeholder="First name">
<button id="firstname-btn" onclick="show()">SHOW</button>
<div class="firstname-show"></div>
<div class="firstname-show"></div>

Related

how to button on click takes all the content from textarea, runs a function and then displays the final value inside new div?

I'm in the learning stages, can you please give me the answer with the explanation.
Also if possible, I would appreciate it if you could explain to me what I have done wrong here and then also show me the better way of doing it.
//ARROW FUNCTION
const reverseNumber = num => (num.toString().split("").reverse().join(""));
let textAreaEl = document.querySelector('#text-area');
let submitButtonEl = document.querySelector('#output-button');
let outputAreaEl = document.querySelector('#output');
submitButtonEl.addEventListener("click", () => {
textAreaValue = reverseNumber(textAreaEl)
outputAreaEl.innerHTML = textAreaValue.value;
});
<form action="">
<label for="object" title="object">JavaScript function that returns a passed string with letters in alphabetical order</label>
<textarea id="text-area" name="object-name" id="" cols="30" rows="5"></textarea>
<input type="button" value="RETURN" id="return-value" />
<div id="output"></div>
</form>
First of all, there is no element with #output-button. You need to fix that.
You are passing the element itself to the reverseNumber(), you should pass the value to function.
I will also suggest you use innerText or textContent instead of innerHTML if the text is plain text (not htmlString).
Demo:
const reverseNumber = num => (num.toString().split("").reverse().join(""));
let textAreaEl = document.querySelector('#text-area');
let submitButtonEl = document.querySelector('#output-button');
let outputAreaEl = document.querySelector('#output');
submitButtonEl.addEventListener("click", () => {
textAreaValue = reverseNumber(textAreaEl.value); //pass value here
outputAreaEl.textContent = textAreaValue; //no need to use value here
});
<form action="">
<label for="object" title="object">JavaScript function that returns a passed string with letters in alphabetical order</label>
<textarea id="text-area" name="object-name" id="" cols="30" rows="5"></textarea>
<input type="button" value="RETURN" id="output-button"/> <!--fix the id here-->
<div id="output"></div>
</form>
Your script should be like this
const reverseNumber = num => (num.toString().split("").reverse().join(""));
console.log(reverseNumber(54321));
let textAreaEl = document.querySelector('#text-area');
let submitButtonEl = document.querySelector('#return-value');
let outputAreaEl = document.querySelector('#output');
submitButtonEl.addEventListener("click", () => {
let textAreaValue = reverseNumber(textAreaEl.value);
outputAreaEl.innerHTML = textAreaValue;
});
First, your document.querySelector('#output-button') is not match with <input type="button" value="RETURN" id="return-value"/>.
Second, you have to use variable declaration keyword to get textAreaEl.value
First of all textarea id is incorrect so querySelector is returning undefined and click event is not attached. I have corrected the button id in html.
You need to use textAreaEl.value to find the textarea text and pass it to reverseNumber function.
//ARROW FUNCTION
const reverseNumber = num => (num.toString().split("").reverse().join(""));
let textAreaEl = document.querySelector('#text-area');
let submitButtonEl = document.querySelector('#output-button');
let outputAreaEl = document.querySelector('#output');
submitButtonEl.addEventListener("click", () => {
textAreaValue = reverseNumber(textAreaEl.value)
outputAreaEl.innerHTML=textAreaValue;
});
<form action="">
<label for="object" title="object">JavaScript function that reverses a number</label>
<textarea id="text-area" name="object-name" id="" cols="30" rows="5"></textarea>
<input type="button" value="RETURN" id="output-button"/>
<div id="output"></div>
</form>

Appending Value to LocalStorage

I want to add new values to localStorage for my Pizza website in which I want the admin to be able to add pizzas. I have this code:
function store() {
var inputName = document.getElementById("name");
localStorage.setItem("name", inputName.value);
var inputDescription = document.getElementById("description");
localStorage.setItem("description", inputDescription.value);
var inputPrice = document.getElementById("price");
localStorage.setItem("price", inputPrice.value);
}
<form onsubmit="store()" id="form1">
<label for="name">Namn:</label><br>
<input class="name" type="text" id="name" name="name" placeholder="Skriv här..."><br>
<label for="description">Beskrivning:</label><br>
<input class="description" type="text" id="description" name="description" placeholder="Skriv här...">
<br>
<label for="price">Pris:</label><br>
<input class="margin-bot" type="text" id="price" name="price" placeholder="Skriv här...">
<br>
<br>
<button form="form1" class="submit-button" type="submit">Lägg Till</button>
</form>
How do I add new pizzas for each time? Everytime I try to add a new value it just replaces the existing one.
function store() {
let inputName = document.getElementById("name");
let inputDescription = document.getElementById("description");
let inputPrice = document.getElementById("price");
let pizzas = []
if(localStorage.getItem("pizzas")){
pizzas = JSON.parse(localStorage.getItem("pizzas"));
}
let pizza = {}
pizza.name = inputName.value;
pizza.description = inputDescription.value;
pizza.price = inputPrice.value;
pizzas.push(pizza)
localStorage.setItem("pizzas", JSON.stringify(pizzas))
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form onsubmit="store()" id="form1">
<label for="name">Namn:</label><br>
<input class="name" type="text" id="name" name="name" placeholder="Skriv här..."><br>
<label for="description">Beskrivning:</label><br>
<input class="description" type="text" id="description" name="description" placeholder="Skriv här...">
<br>
<label for="price">Pris:</label><br>
<input class="margin-bot" type="text" id="price" name="price" placeholder="Skriv här...">
<br>
<br>
<button form="form1" class="submit-button" type="submit">Lägg Till</button>
</form>
</body>
</html>
This should help, first I check the localStorage some pizza is already stored in there or not, if there, then I take that parse it and add one more pizza to it from the form input, if not I create a completely new array and then add the value from the form input then store it in the localStorage.
first it would be better to replace your code to use "objects & arrays" instead of "string variables", like this example i made for you:
function store() {
var inputName = document.getElementById("name");
var inputDescription = document.getElementById("description");
var inputPrice = document.getElementById("price");
return ({
name: inputName.value,
description: inputDescription.value,
price: inputPrice.value
});
}
function updateStore(key = 'pizzas'){
let pizzasArray = JSON.parse(localStorage.get(key)) || [];
pizzasArray.push(store());
localStorage.setItem(key, JSON.stringify(pizzasArray));
}
You can keep it as json array in local storage.For Example;
function addStoreForArray(key, value) {
var storeArrayObj = localStorage.getItem(key);
if(storeArrayObj){
storeArrayObj = JSON.parse(storeArrayObj);
storeArrayObj.push(value);
} else {
storeArrayObj = [];
storeArrayObj.push(value);
}
localStorage.setItem(key, JSON.stringify(storeArrayObj));
}
addStoreForArray('pizzas', {name:'pizzaName', description: 'pizzaDescription', price: 10});
You can create an array to store many pizzas and to check if already exists you can call the getStorage() function and if storagePizzas includes your new pizza then update the value
arrayOfPizzas = []
function storeArray() {
let pizzaCreated = {}
pizzaCreated.name = document.getElementById("name").value;
pizzaCreated.description = document.getElementById("description").value;
pizzaCreated.price = document.getElementById("price").value;
let storageItems = getStorage();
// Check ...
arrayOfPizzas.push(pizzaCreated);
setStorage(arrayOfPizzas);
}
function setStorage(arr){
localStorage.setItem('arrayOfPizzas', JSON.stringify(arr));
}
function getStorage(){
return JSON.parse(localStorage.getItem('arrayOfPizzas');
}
You need to store the pizzas the user has created in an array. You can store the array in local storage, you just need to make sure you can serialize and deserialize it properly
Take the values from the input field
Grab your array of pizzas from local storage
If the array doesn't exist yet, getItem will return null, so you can give it an array to start off with.
Add the new pizza to the array
Save the pizzas array in local storage again.
function store() {
var newPizza = {
name: inputName.value,
description: inputDescription.value,
price: inputPrice.value
}
var pizzas = localStorage.getItem('pizzas')
if (!pizzas) {
pizzas = []
} else {
pizzas = JSON.parse(pizzas)
}
pizzas.push(newPizza)
localStorage.setItem('pizzas', JSON.stringify(pizzas))
}

Just trying out to check whether the value is present in array or not

I am trying to write a function in jQuery.
var arr1 = ["Jcob", "Pete", "Fin", "John"];
var str = $("#fname").val();
if (jQuery.inArray(str, arr1))
$("#lname").text("Bob");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="fname" name="fname">
<input type="text" id="lname" name="lname">
Please check my fiddle here
What it will do it the user will give the value in the first input box the jQuery function will check if the value is present in that array it will fill the second input box with the given text.
Three things:
You need to add an event listener to the first input to constantly keep checking when someone inputs something.
Before selecting elements in the DOM, make sure the DOM is ready.
You don't need jQuery at all here. Like most things, very easy to do without jQuery.
const names = [ "Jcob", "Pete", "Fin", "John" ];
document.addEventListener('DOMContentLoaded', function() {
const fname = document.getElementById('fname');
const lname = document.getElementById('lname');
fname.addEventListener('input', function(event) {
lname.value = names.includes(fname.value) ? 'Bob' : '';
});
});
<input type="text" id="fname" name="fname">
<input type="text" id="lname" name="lname">
If you insist on jQuery (which I do strongly recommend you shouldn't until you are proficient with the native DOM API):
const names = [ "Jcob", "Pete", "Fin", "John" ];
$(document).ready(function() {
const $fname = $('#fname');
const $lname = $('#lname');
$fname.on('input', function(event) {
if ($.inArray($fname.val(), names) > -1) {
$lname.val('Bob');
} else {
$lname.val('');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="fname" name="fname">
<input type="text" id="lname" name="lname">
Try this:
<body>
<input type="text" id="fname" name="fname">
<input type="text" id="lname" name="lname">
<button onclick="checkValue()">Click</button>
<script>
var arr1 = ["Jcob", "Pete", "Fin", "John"];
function checkValue() {
var str = $("#fname").val();
var val = jQuery.inArray(str, arr1);
if (val === -1) {
console.log("no value");
}
else {
$("#lname").val("Bob");
}
}
</script>
</body>

Serialize HTML form to JSON with pure JavaScript

I have seen this method of serializing a form to JSON and it's working fine. My question is: How can I achieve this with pure JavaScript, without using any jQuery code? I am sorry if the question is dumb, but I'm still learning so if anyone can help me, I'll be grateful.
(function ($) {
$.fn.serializeFormJSON = function () {
var objects = {};
var anArray = this.serializeArray();
$.each(anArray, function () {
if (objects[this.name]) {
if (!objects[this.name].push) {
objects[this.name] = [objects[this.name]];
}
objects[this.name].push(this.value || '');
} else {
objects[this.name] = this.value || '';
}
});
return objects;
};
})(jQuery);
$('form').submit(function (e) {
e.preventDefault();
var data = $(this).serializeFormJSON();
console.log(data);
/* Object
email: "value"
name: "value"
password: "value"
*/
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post">
<div>
<label for="name">Name</label>
<input type="text" name="name" id="name" />
</div>
<div>
<label for="email">Email</label>
<input type="text" name="email" id="email" />
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" id="password" />
</div>
<p>
<input type="submit" value="Send" />
</p>
</form>
P.S.
Also in jQuery is this the right way to send multiple JSON objects from user input as One String, because I am searching for a way to do that?
You can try something like this:
function formToJson(){
var formElement = document.getElementsByTagName("form")[0],
inputElements = formElement.getElementsByTagName("input"),
jsonObject = {};
for(var i = 0; i < inputElements.length; i++){
var inputElement = inputElements[i];
jsonObject[inputElement.name] = inputElement.value;
}
return JSON.stringify(jsonObject);
}
This solution works only if you have a single form on the page, to make it more general the function could e.g. take the form element as an argument.
You can use Array.reduce, something like
// get array of all fields and/or selects (except the button)
const getFields = () => Array.from(document.querySelectorAll("input, select"))
.filter(field => field.type.toLowerCase() !== "button");
// get id, name or create random id from field properties
const getKey = field => field.name
|| field.id
|| `unknown-${Math.floor(1000 * Math.random()).toString(16)}`;
// get data, simple object
const getFormData = () => getFields()
.reduce( (f2o, field) => ({...f2o, [getKey(field)]: field.value}), {} );
// log the result
const logResult = txt => document.querySelector("#result").textContent = txt;
// get data, array of field objects
const getMoreFormData = () => getFields()
.reduce( (f2o, field) =>
f2o.concat({
id: field.id || "no id",
name: field.name || "no name",
idGenerated: getKey(field),
type: field.type,
value: field.value }
),
[] );
// handling for buttons
document.addEventListener("click", evt => {
if (evt.target.nodeName.toLowerCase() === "button") {
console.clear();
logResult(/simple/.test(evt.target.textContent)
? JSON.stringify(getFormData(), null, " ")
: JSON.stringify(getMoreFormData(), null, " ")
);
}
} );
<form action="#" method="post">
<div>
<label for="name">Name</label>
<input type="text" name="name" id="name" value="Pete"/>
</div>
<div>
<label for="email">Email</label>
<input type="text" name="email" id="email" value="pete#here.com"/>
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" id="password" />
</div>
<div>
<label>Field without name or id</label>
<input type="number" value="12345" />
</div>
</form>
<p>
<button>Data simple object</button> <button>Data fields array</button>
</p>
<pre id="result"></pre>
Remember that for checkboxes, value attribute can be either on or off string. This is unwanted. Here is my solution, based on this codepen.
let json = Array.from(form.querySelectorAll('input, select, textarea'))
.filter(element => element.name)
.reduce((json, element) => {
json[element.name] = element.type === 'checkbox' ? element.checked : element.value;
return json;
}, {});
OR
let json = {};
Array.from(form.querySelectorAll('input, select, textarea'))
.filter(element => element.name)
.forEach(element => {
json[element.name] = element.type === 'checkbox' ? element.checked : element.value;
});
OR (with typescript)
export type FormJson = {[key: string]: boolean | string};
export const toJson = (form: HTMLFormElement): FormJson =>
Array.from(form.querySelectorAll<HTMLFormElement>('input, select, textarea'))
.filter(element => element.name)
.reduce<FormJson>((json, element) => {
json[element.name] = element.type === 'checkbox' ? element.checked : element.value;
return json;
}, {});
To serialize your form you can do this (note that I added an onsubmit in the form tag):
HTML and JavaScript:
function serializeForm(e) {
e.preventDefault(); // prevent the page to reload
let form = e.target; // get the form itself
let data = new FormData(form); // serialize input names and values
let objSerializedForm = {}; // creating a new object
for (let [name, value] of data) { // iterating the FormData data
objSerializedForm[name] = value; // appending names and values to obj
}
console.log(objSerializedForm);
}
<form action="#" method="post" onsubmit="serializeForm(event)">
<div>
<label for="name">Name</label>
<input type="text" name="name" id="name" />
</div>
<div>
<label for="email">Email</label>
<input type="text" name="email" id="email" />
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" id="password" />
</div>
<p>
<input type="submit" value="Send" />
</p>
</form>
Than you can do whatever you want with your objSerializedForm, getting each value by calling objSerializedForm.name.

Get data for form input array using specific key

So, let's say I have an HTML form like this:
<form id="myForm">
<input type="text" name="dummy">
<input type="text" name="people[0][first_name]" value="John">
<input type="text" name="people[0][last_name]" value="Doe">
<input type="text" name="people[1][first_name]" value="Jane">
<input type="text" name="people[1][last_name]" value="Smith">
</form>
And I want to get a JavaScript array that matches the values of real. For example:
// If there was a sweet function for this...
var people = getFormDataByInputName( 'people' );
// Value of `people` is...
// [
// {
// 'first_name' : 'John',
// 'last_name' : 'Doe'
// },
// {
// 'first_name' : 'Jane',
// 'last_name' : 'Smith'
// }
// ]
Is there any easy way of doing that for just a specific form item (in this case, people)? Or would I have to serialize the entire form an then just extract the element I want?
I also thought of potentially using the following approach:
var formData = new FormData( document.querySelector( '#myForm' ) );
var people = formData.get( 'people' );
But that doesn't appear to work; people is just null after that.
You could do this with plain js using reduce method and return each person is one object.
const form = document.querySelectorAll('#myForm input');
const data = [...form].reduce(function(r, e) {
const [i, prop] = e.name.split(/\[(.*?)\]/g).slice(1).filter(Boolean)
if (!r[i]) r[i] = {}
r[i][prop] = e.value
return r;
}, [])
console.log(data)
<form id="myForm">
<input type="text" name="dummy">
<input type="text" name="people[0][first_name]" value="John">
<input type="text" name="people[0][last_name]" value="Doe">
<input type="text" name="people[1][first_name]" value="Jane">
<input type="text" name="people[1][last_name]" value="Smith">
</form>
function getObject(name, key) {
if(key.includes(name)) {
var splitStr = key.split(/\[|\]/g);
return {
index: splitStr[1],
key: splitStr[3],
}
}
return null;
}
function getFormDataByInputName(name) {
var formData = new FormData( document.querySelector('#myForm'));
var results = [];
for (var key of formData.keys()) {
var obj = getObject(name, key);
if (obj) {
if (results[obj.index]) results[obj.index][obj.key] = formData.get(key);
else results[obj.index] = { [obj.key]: formData.get(key) };
}
}
return results;
}
var people = getFormDataByInputName('people');
console.log(people);
<form id="myForm">
<input type="text" name="dummy">
<input type="text" name="people[0][first_name]" value="John">
<input type="text" name="people[0][last_name]" value="Doe">
<input type="text" name="people[1][first_name]" value="Jane">
<input type="text" name="people[1][last_name]" value="Smith">
</form>
Your code won't work because to HTML/JS name is just a string that it sends to the server when the form is submitted (the name in the name/value pairs). You might think it is arrays, but HTML/JS doesn't.
So no one-liner to get the job done. Try this: In your HTML, add <div class="name"> ...
(UPDATE: thanks for the idea, #Nenad, I've never tried one of these snippets)
var people = [];
$('.name').each(function() {
people.push({
first_name: $('input:nth-child(1)', this).val(),
last_name: $('input:nth-child(2)', this).val()
});
});
console.log(people);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="text" name="dummy">
<div class="name">
<input type="text" value="John">
<input type="text" value="Doe">
</div>
<div class="name">
<input type="text" value="Jane">
<input type="text" value="Smith">
</div>
</form>
Use CSS attribute prefix selector, such as
form.querySelectorAll('[name^="people[]"]')
You can use a for-loop to get all peoples, as such
const MAX_PEOPLES = 2;
const list = [];
for (i = 0; i <= MAX_PEOPLES; i++) {
const eles = form.querySelectorAll(`[name^="people[${i}]`);
if (eles.length !== 2)
break;
list.push({
first_name: eles[0].value,
last_name: eles[1].value
});
}
that yields
[
{
"first_name":"John",
"last_name":"Doe"
},
{
"first_name":"Jane",
"last_name":"Smith"
}
]

Categories

Resources