Trying to remove JSON.stringfy format from output in Javascript - javascript

I trying to get a html-code with javascript to output an array without JSON.stringify. I haven't put in any input validations or anything else, just playing around with arrays and trying to output objects in this array in the html page. I found an example with JSON-stringify which works with my code, but I would like to get the output without JSON-format. For example something like this:
id: 1641231847264,
firstname: asgags
lastname: aasggd
email: sdashga
This code looks like this:
let users = [];
// example {id:1592304983049, Firstname: 'John', Lastname: 'Doe 'Email: john.doe#test.com}
const addUser = (ev) => {
ev.preventDefault(); //to stop the form submitting
let user = {
id: Date.now(),
firstname: document.getElementById('firstname').value,
lastname: document.getElementById('lastname').value,
email: document.getElementById('email').value
}
users.push(user);
document.forms[0].reset(); // to clear the form for the next entries
//document.querySelector('form').reset();
//for display purposes only
console.warn('added', {
users
});
let pre = document.querySelector('#msg pre');
pre.textContent = '\n' + JSON.stringify(users, '\t', 2);
//saving to localStorage
//localStorage.setItem('MyUserList', JSON.stringify(users) );
}
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('btn').addEventListener('click', addUser);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Putting User Input into JS Objects</title>
<style>
.formBox {
padding: 0.5rem 2rem;
}
</style>
</head>
<body>
<form>
<div class="formBox">
<label for="firstname">Firstname</label>
<input type="text" id="firstname" placeholder="Firstname" />
</div>
<div class="formBox">
<label for="lastname">Lastname</label>
<input type="text" id="lastname" placeholder="Lastname" />
</div>
<div class="formBox">
<label for="email">Email</label>
<input type="text" id="email" placeholder="Email" />
</div>
<div class="formBox">
<button id="btn">Click to Add</button>
</div>
<div id="msg">
<pre></pre>
</div>
</form>
</body>
</html>
Have I totally wrong approach for this code or is it just a matter of tweaking the textContent line?
Kind Regards.

It could be a matter of tweaking the assignment:
pre.textContent = users.map(user =>
Object.entries(user).map(([key, value]) =>
`${key}: ${value}`
).join("\n")
).join("\n--------\n");

Loop through the array and properties. Concatenate them all into a string in the format you want, and assign that to the text content.
let users = [];
// example {id:1592304983049, Firstname: 'John', Lastname: 'Doe 'Email: john.doe#test.com}
const addUser = (ev) => {
ev.preventDefault(); //to stop the form submitting
let user = {
id: Date.now(),
firstname: document.getElementById('firstname').value,
lastname: document.getElementById('lastname').value,
email: document.getElementById('email').value
}
users.push(user);
document.forms[0].reset(); // to clear the form for the next entries
//document.querySelector('form').reset();
//for display purposes only
console.warn('added', {
users
});
let pre = document.querySelector('#msg pre');
let msg = users.map(user =>
Object.entries(user).map(([key, value]) => `${key}: ${value}`).join('\n')
).join('\n\n');
pre.textContent = '\n' + msg;
//saving to localStorage
//localStorage.setItem('MyUserList', JSON.stringify(users) );
}
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('btn').addEventListener('click', addUser);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Putting User Input into JS Objects</title>
<style>
.formBox {
padding: 0.5rem 2rem;
}
</style>
</head>
<body>
<form>
<div class="formBox">
<label for="firstname">Firstname</label>
<input type="text" id="firstname" placeholder="Firstname" />
</div>
<div class="formBox">
<label for="lastname">Lastname</label>
<input type="text" id="lastname" placeholder="Lastname" />
</div>
<div class="formBox">
<label for="email">Email</label>
<input type="text" id="email" placeholder="Email" />
</div>
<div class="formBox">
<button id="btn">Click to Add</button>
</div>
<div id="msg">
<pre></pre>
</div>
</form>
</body>
</html>

Related

Making a href variable that changes with text input

I'm trying to make a mailto: link change based on a text input and a button.
I managed to make it work without a href, with just plain text from a paragraph, but i can't manage to make it work on the href.
I get either [object HTMLInputElement] or undefined
HTML
<input type="text" id="email_input"><br>
<span id="links"><a id="email">email</a></span><br>
<input type="button" id="btn" value="Submit"><br>
JAVASCRIPT
var emailIN = document.getElementById('email_input');
var emailOUT = document.getElementById('email');
var emailLink = "mailto:"+emailOUT;
btn.onclick = function(){
/* addressOUT.textContent = addressIN.value; */
/* emailOUT.setAttribute("href",emailIN); */
/* emailOUT.textContent = "mailto:"+emailIN.value; */
/* $("a#email").attr('href','mailto:'+emailIN); */
/* document.querySelector("#email").href=emailLink; */
document.getElementById("email").value = "mailto:"+emailIN
emailOUT.href = "mailto:"+emailIN;
}
Here is an example.
document.getElementById('btn').addEventListener('click', function() {
const emailInput = document.getElementById('email_input');
const emailLink = document.getElementById('email');
const href = emailInput.value != '' ? 'mailto:' + emailInput.value : '';
if (href.length > 0) {
emailLink.setAttribute('href', href);
console.log(`Link href is change to ${href}`);
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<div class="my-5">
<div class="mb-3">
<label for="email_input" class="form-label">Email address</label>
<input class="form-control" id="email_input" placeholder="name#example.com" />
</div>
<div class="mb-3">
<a id="email" href="">Email Link</a>
</div>
<div class="mb-3">
<button type="button" id="btn" class="btn btn-primary btn-md">Submit</button>
</div>
</div>
</div>
</body>
</html>

I want to get a form and save it in local storage, but how?

Heyy,
i'm a beginner in writing with java script and i'm trying to copy Instagram, soo I need help in form and validation stuff and I also want to save it with local Storage.
I can't find the Problem in my Code and I don't know how to write the local Storage Code.
scripts.js
const VornameInput = document.getElementById("Vorname-input");
const NachnameInput = document.getElementById("Nachname-input");
const GeburtstagInput = document.getElementById("Geburtstag-input");
const ueberMichInput = document.getElementById("ueber-mich");
const SpeicherButton = document.getElementById("enter-button");
const EmailInput =document.getElementById("email-input");
const EingabeInput = document.getElementById("Eingabe");
SpeicherButton.addEventListener("click", enterEvent);
const Vorname = VornameInput.value;
const Nachname = NachnameInput.value;
const Geburtstag = GeburtstagInput.value;
const ueberMich = ueberMichInput.value;
const Email = EmailInput.value;
function felderInKonsoleAusgeben () {
console.log("Vorname:", Vorname);
console.log("Nachname:", Nachname);
console.log("Geburtstag:", Geburtstag);
console.log("UeberMich:", ueberMich);
console.log("Email:", EmailInput);
}
function validierung(Vorname,Nachname,Geburtstag) {
if (VornameInput.value == "" || NachnameInput.value == "" || isNaN(Number(GeburtstagInput.valueAsNumber))){
alert ("Bitte fülle alle Felder aus! ");
return false;
}
else
alert ("Eingaben wurden gespeichert");
return true; }
function validierungEmail (EmailInput){
var validRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
if (input.value.match(validRegex)) {
alert("Gültige Email Adresse!");
return true;
} else {
alert("Ungültige Email Adresse!");
return false; }
function enterEvent(evt) {
evt.preventDefault();
felderInKonsoleAusgeben();
validierung(Vorname, Nachname, Geburtstag);
validierungEmail(EmailInput);
}
html
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="Das wird einmal ein Instagram Clone" />
<meta name="keywords" content="Instagram, Instagram 2.0, Clone" />
<meta name="author" content="Emily Schlachter" />
<link rel="stylesheet" href="css/style.css" />
<script src="scripts.js" defer></script>
<title>Instagram 2.0</title>
</head>
<body>
<header>
<div > <a href="instagram-clone_schlachter.html"> <h1>Gramml</h1> </a ></div>
</header>
<ul id="navibereich">
<li id="navi01"> <h2>Mein Profil </h2> </li>
<li id="navi02"> <h2>Entdecken</h2> </li>
<li id="navi01"> <h2>Upload Picture</h2> </li>
</ul>
<div class="label">
<label>Suche:</label>
<input type="text"/>
</div>
<main>
<!-- Eingabefeld -->
<div class="Eingabe" id="Eingabe">
<div class="field">
<input id="Vorname-input" type="text" name="vorname-input" placeholder="Vorname" />
</div>
<div class="field">
<input id="Nachname-input" type="text" name="Nachname-input " placeholder="Nachname" />
</div>
<div class="field">
<input id="email-input" type="text" name="email-input" placeholder="Email-Adresse" />
</div>
<div class="field">
<input id="Geburtstag-input" type="date" name="Geburtstag-input" placeholder="Geburtsdatum" />
</div>
<label>Über mich: <br> </label>
<textarea name="ueber-mich" id="ueber-mich" cols="40" rows="5" maxcols="35" placeholder="Über mich:" > </textarea>
</div>
<div class="Formelles">
<p> <input type="checkbox" name="AGB" value="News"> Datenschutzerklärung und AGB akzeptieren. </p>
</div>
<button id="enter-button" class=" button" type="submit">
Speichern
</button>
</main>
</body>
</html>
I just want to get a validation formand to save the Input in local Storage.
Thanks for your help!
You can add all needed information into an obejct like
const personInfo = {
"vorname": VornameInput.value,
"nachname": ...,
"geburtstag": ...,
"uebermich": ...,
"email": ...
}
Then you can store this object with a key in the local storage with
localStorage.setItem('personInfo',JSON.stringify(personInfo));
To get it back use
const pInfo = localStorage.getItem('personInfo');
Have a look here https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage to learn more about localstorage

How to auto populate form fields with json using one select?

I have a form with a select field (for this case is the first name), I want to select one of the options and with that data selected, the other fiels should be auto completed.
The data is comming from an API.
I'm able to have the dropdown working but whenever I select one option the fields aren't being populated.
Can someone help me, please?
This is my javascript:
document.addEventListener('DOMContentLoaded',() => {
const nomeSelectDrop = document.getElementById('nome');
const sobrenome = document.getElementById('sobrenome');
const email = document.getElementById('email');
const password = document.getElementById('password');
fetch('http://localhost:5000/user')
.then(res => {
return res.json();
})
.then(data => {
let output = "";
data.forEach(users => {
output += `<option value = "${users.firstName}">${users.firstName}</option>`;
})
nomeSelectDrop.innerHTML = output;
})
.catch(err => {
console.log(err);
})
nome.addEventListener('change', (event) => {
sobrenome.innerHTML = event.target.lastName.value;
email.innerHTML = event.target.email.value;
password.innerHTML = event.target.password.value;
})
})
This is my html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Form Exercise</title>
</head>
<body>
<form class="formulario">
<div class="field">
<label for="nome">Nome:</label>
<select id="nome" name="nome"></select>
</div>
<div class="field">
<label for="sobrenome">Sobrenome:</label>
<input type="text" id="sobrenome" name="sobrenome" placeholder="sobrenome" required>
</div>
<div class="field">
<label for="email">E-Mail:</label>
<input type="email" id="email" name="email" placeholder="e-mail" required>
</div>
<div class="field">
<label for="password">Password:</label>
<input type="password" id="password" name="password" placeholder="password" required>
</div>
<div class="buttons">
<input type="submit" name="atualizar" value="Atualizar">
<input type="submit" name="eliminar" value="Eliminar">
</div>
</form>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
Be aware that some of the #ids and names in HTML has been changed (I think slower reading foreign words -- I'm dumb that way 😕). HTMLFormElement and HTMLFormControlsCollection interfaces were used to reference <form>, <input>, and <select>. The most important part is declaring a variable outside of fetch(), then defining that variable as the data within fetch() which brings the data within scope for functions, expressions, etc outside of fetch().
Details are commented in example below
// Reference the <form>
const exc = document.forms.exc;
document.addEventListener('DOMContentLoaded', (e) => {
/*
Collect all <select>,<fieldset>,<input> into a HTMLCollection
*/
let io = exc.elements;
// Declare a variable outside of fetch()
let users;
fetch('https://my.api.mockaroo.com/userlist.json?key=3634fcf0')
.then(res => {
return res.json();
})
.then(data => {
/* IMPORTANT
Define users as JSON data -- now the JSON is in scope within
this event handler
*/
users = data;
let output = "";
data.forEach(user => {
output += `<option value = "${user.first}">${user.first}</option>`;
});
/*
Use insertAdjacentHTML() instead of innerHTML -- it doesn't destroy
content it adds to content.
*/
io.first.insertAdjacentHTML('beforeend', output);
})
.catch(err => {});
/*
Bind <form> to the change event
*/
exc.addEventListener('change', (e) => {
// Reference the tag user is interacting with
const sel = e.target;
/*
If the tag the user is interacting with is a <select>...
*/
if (sel.matches('select')) {
// Find the index of selected <option>
let idx = sel.selectedIndex;
/*
users = JSON
Reference index of users with index of selected <option>
*/
io.last.value = users[idx].last;
io.email.value = users[idx].email;
io.password.value = users[idx].password;
}
});
});
html {font: 2ch/1.25 'Segoe UI'}
fieldset {max-width: max-content;}
legend {font-size:1.25rem}
input, select, label {display: inline-block; margin: 2px; font: inherit;}
input:not([type='submit']) {width: 32ch}
[type='submit'] {float: right; cursor: pointer;}
select {width: 33ch}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="style.css" rel="stylesheet">
<title>Form Exercise</title>
</head>
<body>
<form id="exc">
<fieldset class="field">
<legend>User Registration</legend>
<label for="first">First Name: </label><br>
<select id="first" name="first">
<option selected disabled>Select a user</option>
</select><br>
<label for="last">Last Name:</label><br>
<input id="last" name="last" required><br>
<label for="email">E-Mail:</label><br>
<input id="email" name="email" type="email" placeholder="user#mail.com" required><br>
<label for="password">Password:</label><br>
<input id="password" name="password" type="password" placeholder="Min 8 characters" required>
<menu class="buttons">
<input name="update" type="submit" value='Update'>
<input name="remove" type="submit" value="Remove">
</menu>
</fieldset>
</form>
<script src="app.js"></script>
</body>
</html>

Javascript Mouseover button

I think I'm close to getting this right but I can't figure out how to change the colour of my submit button when the user hovers over it, I'm very new too javascript so any help would be greatly appreciated
here is my code:
<html>
<head>
<title>JavaScript</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
function getName(){
var name;
name = window.prompt("Enter your name", "");
greeting = "User Information for " + name;
var txt= document.getElementById('txtWelcome');
txt.innerHTML=greeting;
}
function over() {
document.getElementById("Submit").style.background = 'Blue';
}
function out() {
document.getElementById("Submit").style.background = 'Yellow';
}
</script>
</head>
<body onload="getName()">
<form class="basic_form">
<h1 id="txtWelcome"></h1>
<p>Please input your login details</p>
<fieldset>
<label class="form_labels">Username:</label>
<input class="form_fields" type="text" name="username"><br>
<label class="form_labels">E-Mail:</label>
<input class="form_fields" type="email" name="email"><br>
<label class="form_labels">Password:</label>
<input class="form_fields" type="password" name="password">
<input class="form_buttons" type="Submit" value="Submit"><br>
</fieldset>
</form>
</body>
Here's the javascript solution:
var submitButton = document.getElementById('submit');
submitButton.addEventListener('mouseover', function() {
this.style.backgroundColor='blue';
});
submitButton.addEventListener('mouseout', function() {
this.style.backgroundColor='yellow';
});
https://jsfiddle.net/hsxdkkp6/
But why not just use css?
input[type=submit]:hover {
background-color: red;
}
https://jsfiddle.net/jkkj8dvt/

HTML5 Storage Not working

I am working on forwarding data from the current page to the same next page i.e. whenever the page is loaded again, the code checks if there is any such storage, if it is then it loads the values in text box. I am not able to get it to work Below is the code -
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript">
function values()
{
if(localStorage.getItem(pranav))
{
document.getElementById(FName).innerText= sessionStorage.getItem(pranav);
document.getElementById(OName).innerText= sessionStorage.getItem(k);
}
else
{
sessionStorage.setItem("pranav", "P");
sessionStorage.setItem("k", "P");
return;
}
}
</script>
</head>
<body>
<form name="myform" action="Idea.html" onload="values(this.form)">
<label>Please Enter Your Full Name = </label><input type="text" name="FName" id="FName" />
<label>Please Enter Your Current Organization</label><input type="text" name="OName" id="OName" />
<input type="submit" value="Submit" onclick="values(this.form)" />
</form>
</body>
</html>
Kindly help me as to why this is not working?
You haven't declared the pranav and k variables you used. Also when you are assigning a value to an input field you should use the .value property instead of .innerText.
Also you might consider splitting your code in 2 functions:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript">
function loadValues() {
var data = localStorage.getItem('data');
if(data) {
data = JSON.parse(data);
document.getElementById('FName').value = data.firstName;
document.getElementById('OName').value = data.lastName;
}
}
function saveValues() {
var data = {
firstName: document.getElementById('FName').value,
lastName: document.getElementById('OName').value
};
localStorage.setItem('data', JSON.stringify(data));
}
</script>
</head>
<body onload="loadValues()">
<form name="myform" action="Idea.html" onsubmit="saveValues()">
<label>Please Enter Your Full Name = </label>
<input type="text" name="FName" id="FName" />
<label>Please Enter Your Current Organization</label>
<input type="text" name="OName" id="OName" />
<input type="submit" value="Submit" />
</form>
</body>
</html>

Categories

Resources