I have a basic HTML form that takes input from the user about his age, gender, dob, email and contact number. I save it into the local storage as employeeData by making it an object in an array. [{},{},{}]. I also add a User_id that is calculated by a random function generator and display it using the Javascript. An example is mentioned below.
[
{
"U_Id": "1a9f1268-9c74-4cfb-971c-f595cb4a40e1",
"Name": "dsgfdsfds",
"Gender": "Male",
"Dob": "2022-02-04",
"Email": "lsngldfsng#gmail.com",
"Tel": "9958111111",
"Hobbies": [
"Coding"
]
},
{
"U_Id": "d7e5b305-4604-4831-b168-96136a7b4ea5",
"Name": "dghdghdhddh",
"Gender": "Male",
"Dob": "2022-02-04",
"Email": "lsngldfsn232g3#gmail.com",
"Tel": "8989092345",
"Hobbies": [
"Coding",
"Gaming"
]
}
]
I create the object to store using const formData = new FormData(form);.
Now when I am fetching the data to display it back into the form, I am using the following function -
const empIndex = employeeData[index];
const form = document.getElementById("form");
for(let i=0;i<form.length;i++){
console.log(form.elements[i])
console.log(empIndex[keys[i]]);
form.elements[i].value = empIndex[keys[i]];
}
const gender = empIndex.Gender;
const hobbies = empIndex.Hobbies;
form.elements[0].value = empIndex.Name;
But the issue is, the radio buttons are treated as 2 different entities and not as 1, which is why I have to individually set the name as Name and what happens is shown below-
This is how the console looks after the logs
I need to know why does the HTML not deals the radio buttons as a group and a single entity, but rather makes it seperate entities, forcing me to input values with the loop into all the form elements, meanwhile I have created a group for a reason to be able to treat it as a single entity, just like an array. An array is a group of entities, but the HTML radio button group is not a group? Anyway to go about it?
console.log("i am inside the script");
var incorrect = true;
function uuidv4() {
return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) =>
(
c ^
(crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
).toString(16)
);
}
function namechecker(name) {
if (name == "" || name.length < 5 || name.length > 45) {
document.getElementById("namehidden").style.display = "contents";
} else {
document.getElementById("namehidden").style.display = "none";
incorrect = false;
}
}
function dobChecker(dob) {
if (!dob) {
document.getElementById("dobhidden").style.display = "contents";
} else {
document.getElementById("dobhidden").style.display = "none";
incorrect = false;
}
}
function emailChecker(email) {
const emailRegex =
/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!(email && emailRegex.test(email))) {
document.getElementById("emailhidden").style.display = "contents";
incorrect = true;
} else {
document.getElementById("emailhidden").style.display = "none";
incorrect = false;
}
}
function phChecker(phone) {
const phRegex = /^[6-9]\d{9}$/;
if (!phRegex.test(phone)) {
console.log("Phone number is incorrect");
document.getElementById("telhidden").style.display = "contents";
incorrect = true;
} else {
document.getElementById("telhidden").style.display = "none";
incorrect = false;
}
}
function incorrectForm(name, dob, email, tel) {
console.log(incorrect);
namechecker(name);
dobChecker(dob);
emailChecker(email);
phChecker(tel);
if (!incorrect) return false;
else return true;
}
function Init(form) {
const formData = new FormData(form);
const name = formData.get("name");
const dob = formData.get("dob");
const gender = formData.get("gender");
const email = formData.get("email");
const tel = formData.get("tel");
const markedCheckbox = document.getElementsByName("hobbies");
const hobbies = [];
for (var checkbox of markedCheckbox) {
if (checkbox.checked) {
hobbies.push(checkbox.value);
}
}
if (incorrectForm(name, dob, email, tel)) {
console.log(
"The form is incorrect. Kindly check and input correct entries."
);
alert("The Form is Incorrect. Kindly check the values and fill it correctly.")
} else {
return {
U_Id: uuidv4(),
Name: name,
Gender: gender,
Dob: dob,
Email: email,
Tel: tel,
Hobbies: hobbies,
};
}
}
const but = document.getElementById("button");
console.log(but);
but.addEventListener("click", (event) => {
event.preventDefault();
console.log("i clicked the button");
const f = document.getElementById("form");
const object = Init(f);
if (object) {
if (!localStorage.getItem("employeeData")) {
localStorage.setItem("employeeData", JSON.stringify([object]));
} else {
const existing = JSON.parse(localStorage.getItem("employeeData"));
existing.push(object);
localStorage.setItem("employeeData", JSON.stringify(existing));
}
console.log(localStorage.getItem("employeeData"));
}
// calling another script from the button if the form is correct.
if (!incorrect) {
console.log("hi i am in basic!");
var tdStyle = "border:1px solid green;min-width:110px;";
const table = document.createElement("table");
table.setAttribute("style", "table-layout: fixed; width:max-content");
const tr = document.createElement("tr");
const employeeData = JSON.parse(localStorage.getItem("employeeData"));
console.log(employeeData);
if (employeeData){
const keys = Object.keys(employeeData[0]);
for (let i = 0; i < keys.length; i++) {
const th = document.createElement("th");
th.innerText = keys[i];
th.setAttribute("style", tdStyle);
tr.appendChild(th);
}
const action = document.createElement("th");
action.innerText = "Actions";
action.setAttribute("style", tdStyle);
tr.appendChild(action);
const thead = document.createElement("thead");
thead.appendChild(tr);
table.appendChild(thead);
const tbody = document.createElement("tbody");
function btnCreator(index) {
const buttontd = document.createElement("td");
const editBtn = document.createElement("button");
editBtn.setAttribute("id" , "edit" + index);
editBtn.innerText = "Edit";
editBtn.setAttribute("style","margin-inline-end:10px");
buttontd.setAttribute("style", tdStyle);
const delBtn = document.createElement("button");
delBtn.setAttribute("id", "delete" + index);
delBtn.innerText = "Delete";
editBtn.addEventListener("click", ()=>editListener(index));
buttontd.appendChild(editBtn);
buttontd.appendChild(delBtn);
return buttontd;
}
function editListener(index){
const empIndex = employeeData[index];
const form = document.getElementById("form");
for(let i=0;i<form.length;i++){
console.log(form.elements[i])
console.log(empIndex[keys[i]]);
form.elements[i].value = empIndex[keys[i]];
}
const gender = empIndex.Gender;
const hobbies = empIndex.Hobbies;
form.elements[0].value = empIndex.Name;
document.getElementById("chkbx1").checked = false;
document.getElementById("chkbx2").checked = false;
document.getElementById("chkbx3").checked = false;
document.getElementById("rdbox1").checked = true;
document.getElementById("rdbox2").checked = false;
if (gender =="Female"){
document.getElementById("rdbox1").checked = false;
document.getElementById("rdbox2").checked = true;
}
hobbies.forEach((element)=>{
switch (element){
case "Gaming":
document.getElementById("chkbx1").checked = true;
break;
case "Coding":
document.getElementById("chkbx2").checked = true;
break;
case "Music":
document.getElementById("chkbx3").checked = true;
break;
default:
break;
}
})
}
employeeData.forEach(function (item, index, arr) {
const tr2 = document.createElement("tr");
for (let i in item) {
const td = document.createElement("td");
td.innerText = item[i];
td.setAttribute("style", "border:1px solid green; width:100%");
tr2.appendChild(td);
}
tr2.appendChild(btnCreator(index));
tbody.appendChild(tr2);
table.appendChild(tbody);
});
const basicdiv = document.getElementsByClassName("basic")[0];
basicdiv.appendChild(table);}
else{
}
});
body{
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
.top-div{
display: flex;
margin-top: 200px;
font-size: larger;
font-weight: bold;
justify-content: center;
align-items: center;
flex-direction: column;
width: 100%;
}
.mid-div{
display: flex;
flex-direction: column;
background-color: #1282cc;
color: black;
border-top-left-radius: 4px;
border-top-right-radius: 4px;
width: 75%;
}
.bot-div{
background-color: white;
border: solid thin #1282cc;
border-radius: 4px;
padding-bottom: 2%;
}
form{
width: 100%;
display: flex;
flex-direction: column;
}
.namelabel{
margin-top: 10px;
}
.col-25 {
float: left;
text-align: right;
width: 22%;
margin-top: 6px;
}
.col-75 {
float: right;
width: 73%;
margin-right: 2%;
}
.required{
color: red;
}
.dob ,.tel,.email{
width: 100%;
}
.vertical{
margin: 0 2.5% 0 0;
}
#button{
background-color: #1282cc;
color: white;
margin-top: 5%;
padding: 1% 2%;
border: #1282cc solid thin;
border-radius: 4px ;
}
span.items{
color:black;
padding-left: 0;
}
div span{
color: white;
font-size: medium;
font-weight: lighter;
padding:15px;
}
* {
box-sizing: border-box;
}
input[type=text] {
width: 100%;
height: 25px;
border: 1px solid #ccc;
margin: 32px 12px 12px 0;
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
}
input[type=radio]{
margin: 23px 12px 12px 0;
}
input[type=date] {
margin: 20px 12px 12px 0;
border: 1px solid #ccc;
height: 25px;
}
input[type=email] {
margin: 23px 12px 12px 0;
border: 1px solid #ccc;
height: 25px;
}
input[type=tel]{
margin: 23px 12px 12px 0;
border: 1px solid #ccc;
height: 25px;
}
label {
padding: 12px 12px 12px 0;
display: inline-block;
}
.hidden{
font-size: small;
color: red;
display: none;
}
.container {
background-color: white;
padding: 20px;
border: blue 1px solid;
}
/* Clear floats after the columns */
.row:after {
content: "";
display: table;
clear: both;
}
#media screen and (max-width:840px) {
.parent{
display: flex;
flex-direction: column;
}
.col-75{
margin: 0;
margin-left: 5%;
}
.col-25{
width: 100%;
margin: 0%;
padding: 12px;
text-align: left;
}
input[type=text] {
margin: 10px 12px 12px 0;
}
input[type=email] {
margin: 10px 12px 12px 0;
}
input[type=tel]{
margin: 10px 12px 12px 0;
}
input[type=radio]{
margin: 5px 5px 0 0;
}
.mf{
display: flex;
}
}
/* Adding styling for basic table */
.basic{
display: flex;
flex-direction: row;
width: 100%;
overflow-x: auto;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css" />
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Employee Data</title>
<script src="basic.js" defer></script>
</head>
<body>
<div class="top-div">
<h2>Employee</h2>
<div class="mid-div">
<span>Add Employee</span>
<div class="bot-div">
<form action="" id="form">
<div class="parent">
<div class="col-25">
<label class="namelabel"> Name:</label>
</div>
<div class="col-75">
<input name="name" type="text" maxlength="45" minlength="5" placeholder="Your Name" />
<label class="hidden" id="namehidden">This field is required</label>
</div>
</div>
<div class="parent">
<div class="col-25">
<label> Gender:</label>
</div>
<div class="col-75 mf">
<div>
<input type="radio" class="radio" name="gender" value="Male" id="rdbox1" checked /><span class="items">Male</span>
</div>
<div><input type="radio" class="radio" name="gender" value="Female" id="rdbox2"/><span class="items">Female</span>
</div>
</div>
</div>
<div class="parent">
<div class="col-25">
<label> Date of Birth:</label>
</div>
<div class="col-75">
<input type="date" name="dob" class="dob" /><br>
<label class="hidden visible" id="dobhidden">This field is required</label>
</div>
</div>
<div class="parent">
<div class="col-25">
<label> Email:</label>
</div>
<div class="col-75">
<input type="email" placeholder="Enter Email" name="email" class="email" />
<br>
<label class="hidden" id="emailhidden">This field is required</label>
</div>
</div>
<div class="parent">
<div class="col-25">
<label> Phone:</label>
</div>
<div class="col-75">
<input type="tel" placeholder="Enter phone" name="tel" class="tel" />
<br>
<label class="hidden" id="telhidden">This field is incorrect</label>
</div>
</div>
<div class="parent">
<div class="col-25">
<label class="padding"> Hobbies:</label>
</div>
<div class="col-75 vertical" name="hobbies">
<input class="chkbox" type="checkbox" name="hobbies" value="Gaming" id="chkbx1" /><span
class="items">Gaming</span> <br>
<input class="chkbox" type="checkbox" name="hobbies" value="Coding" id="chkbx2" /><span
class="items">Coding</span> <br>
<input class="chkbox" type="checkbox" name="hobbies" value="Music" id="chkbx3" /><span
class="items">Music</span> <br>
</div>
</div>
<div>
<div class="col-75">
<button type="submit" id="button">Submit</button>
</div>
</div>
</form>
</div>
</div>
<h2>Basic</h2>
<div class="mid-div">
<span>Add Employee</span>
<div class="bot-div basic">
</div>
</div>
<h2>Advanced</h2>
<div class="mid-div">
<span>Add Employee</span>
<div class="bot-div">
</div>
</div>
</div>
</div>
</body>
<script src="script.js"></script>
</html>
const keys = Object.keys(employeeData[0]);
const form = document.getElementsByName("form")[0];
console.log("form in edit listener ", form);
for (let i = 0; i < form.length; i++) {
const formElement = document.forms[0].elements[i];
if (formElement.type == "radio") {
formElement.checked = formElement.value === emp.Gender;
if (!formElement.checked) {
document.forms[0].elements[i + 1].checked = true;
}
i += 1;
continue;
}
if (formElement.type == "checkbox") {
for (let j = 0; j < emp.Hobbies.length; j++) {
if (!formElement.checked) {
formElement.checked = formElement.value === emp.Hobbies[j];
}
}
}
if (formElement.type != ("checkbox" || "radio")) {
form.elements[i].value = emp[keys[i]];
if (formElement.type == "text") {
formElement.value = emp.Name;
}
}
}
This way I was able to check formElement.checked = formElement.value === emp.Gender; and set the value by using formElement.type == "radio". I was unable to think about this and it finally hit me later when I was strolling around to find a solution. This seems such a small issue but the question still remains. Why is the button group NOT A GROUP???
Related
I've been working on a contact form with validation. Im using constraint validation api, and I have these files which kinda works the way I want, but I wonder if there's a way I can make the errorboxes red when there's an error, and white (or hidden) when there's no validation error. There's probably some code which is unneccesary, and I plan to clean it up when i'm satisfied with the functionality, but now it looks like i have errors everywhere when everything is valid.
const form = document.getElementsByTagName('form')[0];
const email = document.getElementById('mail');
const emailError = document.querySelector('#mail + span.error');
const navn = document.getElementById('navn');
const navnError = document.querySelector('#navn + span.error');
const telefon = document.getElementById('telefon');
const telefonError = document.querySelector('#telefon + span.error')
const message = document.getElementById('message');
const messageError = document.querySelector('#message + span.error')
const personvern = document.getElementById('personvern');
const personvernError = document.querySelector('#personvern + span.error')
// THIS DIV WILL CONTAIN ERROR MESSAGES
const errOutput = document.querySelector('.errorsOutput')
email.addEventListener('input', function(event) {
if (email.validity.valid) {
emailError.innerHTML = '';
emailError.className = 'error';
} else {
showError();
}
});
navn.addEventListener('input', function(event) {
if (navn.validity.valid) {
navnError.innerHTML = '';
navnError.className = 'error';
} else {
showError();
}
})
telefon.addEventListener('input', function(event) {
if (telefon.validity.valid) {
telefonError.innerHTML = '';
telefonError.className = 'error';
} else {
showError();
}
})
message.addEventListener('input', function(event) {
if (message.validity.valid) {
messageError.innerHTML = '';
messageError.className = 'error';
} else {
showError();
}
})
form.addEventListener('submit', function(event) {
if (!email.validity.valid || !navn.validity.valid || !telefon.validity.valid || !message.validity.valid) {
showError();
event.preventDefault();
}
});
function showError() {
// EMPTY ERRORS DIV
errOutput.innerHTML = ''
if (navn.validity.valueMissing) {
navnError.textContent = '* Du må fylle inn navnet ditt';
} else if (navn.validity.tooShort) {
navnError.textContect = '* Du må fylle inn hele navnet ditt'
}
// OUTPUT ERRORS IN DIV
if (navnError.textContent != '') {
errOutput.innerHTML += '<p>Navn error!</p>'
}
if (email.validity.valueMissing) {
emailError.textContent = '* Vennligst fyll inn e-posten din';
} else if (email.validity.typeMismatch) {
emailError.textContent = '* Dette er ikke en gyldig e-postadresse.';
} else if (email.validity.tooShort) {
emailError.textContent = `* Email should be at least ${ email.minLength } characters; you entered ${ email.value.length }.`;
}
// OUTPUT ERRORS IN DIV
if (emailError.textContent != '') {
errOutput.innerHTML += '<p>Email error!</p>'
}
if (telefon.validity.valueMissing) {
telefonError.textContent = '* Du må fylle inn telefonnummeret ditt'
} else if (telefon.validity.tooShort) {
telefonError.textContent = '* Du mangler ett eller flere tall. Vennligst dobbeltsjekk.'
}
// OUTPUT ERRORS IN DIV
if (telefonError.textContent != '') {
errOutput.innerHTML += '<p>Telefonnummer error!</p>'
}
if (message.validity.valueMissing) {
messageError.textContent = '* Beskjeden mangler, vennligst fyll inn'
} else if (message.validity.tooShort) {
messageError.textContent = `* Beskjed må være minst ${ message.minLength } tegn.`;
}
// OUTPUT ERRORS IN DIV
if (messageError.textContent != '') {
errOutput.innerHTML += '<p>Beskjed error!</p>'
}
}
// Set the styling appropriately
emailError.className = 'error active';
navnError.className = 'error active';
telefonError.className = 'error active';
messageError.className = 'error active';
personvernError.className = 'error active';
body {
width: 600px;
padding: 0;
margin: 0 auto;
font-family: 'Open Sans', sans-serif;
font-weight: 400;
font-size: 1.1rem;
}
p * {
display: block;
}
input[type=text] {
-webkit-appearance: none;
appearance: none;
min-width: 500px;
width: 100% !important;
padding: 15px;
border: 1px solid #333;
margin: 0;
font-family: inherit;
font-size: 90%;
box-sizing: border-box;
}
input[type=email] {
-webkit-appearance: none;
appearance: none;
min-width: 500px;
width: 100% !important;
padding: 15px;
border: 1px solid #333;
margin: 0;
font-family: inherit;
font-size: 90%;
box-sizing: border-box;
}
input[type=tel] {
-webkit-appearance: none;
appearance: none;
min-width: 500px;
width: 100% !important;
padding: 15px;
border: 1px solid #333;
margin: 0;
font-family: inherit;
font-size: 90%;
box-sizing: border-box;
}
/* This is our style for the invalid fields */
input:invalid {
border-color: #900;
background-color: #FDD;
}
input:focus:invalid {
outline: none;
}
/* This is the style of our error messages */
.error {
width: 100%;
padding: 15px;
min-height: 20px;
font-size: 100%;
color: white;
background-color: #900;
display: flex;
justify-content: flex-start;
margin: 1rem 0;
}
.error.active {
padding: 0;
}
.errorsOutput {
background-color: #ac0606;
color: white;
margin: 0 0 5px 0;
}
.errorsOutput p {
padding: 1px;
}
<!DOCTYPE html>
<html>
<head>
<script src="jquery-3.6.0.min.js"></script>
<script src="kontaktskjema.js"></script>
<link rel="stylesheet" href="kontakt.css">
<meta charset="utf-8">
<title>Kontaktskjema</title>
</head>
<body>
<!-- THIS DIV WILL CONTAIN ERROR MESSAGES -->
<div class="errorsOutput">
</div>
<div class="kontaktskjema">
<div class="error">
<form novalidate>
<p>
<label for="navn">
<span>Navn:</span>
<input type="text" id="navn" name="navn" required minlength="3">
<span class="error" aria-live="polite"></span>
</label>
</p>
</div>
<div class="error">
<form novalidate>
<p>
<label for="name">
<span>Telefonnummer:</span>
<input type="tel" id="telefon" name="telefon" required minlength="8" required maxlength="8">
<span class="error" aria-live="polite"></span>
</label>
</p>
</div>
<div class="error">
<form novalidate>
<p>
<label for="mail">
<span>E-post:</span>
<input type="email" id="mail" name="mail" required minlength="6">
<span class="error" aria-live="polite"></span>
</label>
</p>
</div>
<div class="error">
<form novalidate>
<p>
<label for="message">
<span>Beskjed:</span>
<input type="text" id="message" name="message" required minlength="10">
<span class="error" aria-live="polite"></span>
</label>
</p>
</div>
<form>
<p>
<label for="personvern">
<div class="personvern">
<span>Personvern:</span>
<br>
<input type="checkbox" id="personvern" name="personvern" required>
<span>Jeg har lest og godkjent Personvernserklæringen</span>
<span class="error" aria-live="polite"></span>
</div>
</label>
</p>
<button>Send</button>
</form>
</div>
<script src="kontakt.js"></script>
</body>
</html>
Thanks!
The way I'd do it, is through application-defined element attributes.
CSS totally support attribute selectors. If you set some attribute of the div element to a certain value, say data-validation-error=true, then in your CSS
div[data-validation-error="true"] {
/* red */
}
div[data-validation-error="ok"] {
display: none; /* hidden */
}
and in JavaScript, use the setAttribute function on the div you want to control.
Notice I used the data- prefix. This is the standard HTML attribute prefix for user/application-defined attributes.
I am trying to solve my problem with if-else in Javascript.
I would highly appreciate your help.
I wanted to filter the name via gender, also safe the keys - woman / man to local storage.
But I can not find out how to make if-else clause.
Can someone help me?
There is also the link:
https://drive.google.com/file/d/1RNJxbiU_DsFTCqGJWgxpepCgdOhGuzIj/view?usp=sharing
Thanks a lot, it means world to me, I am new here. :-)
$(document).ready(function() {
function displayName() {
let safeNameVal = localStorage.getItem('woman');
let safeName;
if (safeNameVal) {
safeName = JSON.parse(safeNameVal);
} else {
safeName = [];
}
//find list
let nameUl = $('#list_2');
nameUl.empty(); //.html('')
//making list
$.each(safeName, function(key, name) {
let nameLi = $('<li></li>');
nameLi.text(name);
//remove link
let jmenoRemoveLink = $('x');
jmenoRemoveLink.click(function(e) {
e.preventDefault();
//name
let safeNameVal = localStorage.getItem('woman');
let safeName;
if (safeNameVal) {
safeName = JSON.parse(safeNameVal);
} else {
safeName = [];
}
//remove
safeName.splice(key, 1);
//safe name
localStorage.setItem('woman', JSON.stringify(safeName));
//display name
displayName();
});
nameLi.append(jmenoRemoveLink);
nameUl.append(nameLi);
});
}
$('#formular').submit(function(e) {
e.preventDefault();
let zadaneJmeno = $('#name').val();
if (zadaneJmeno) {
//safe
let safeNameVal = localStorage.getItem('woman');
let safeName;
if (safeNameVal) {
safeName = JSON.parse(safeNameVal);
} else {
safeName = [];
}
safeName.push(zadaneJmeno);
localStorage.setItem('woman', JSON.stringify(safeName)); /// ["Tom"]
//list
displayName();
$('#name').val('');
} else {
// alert
alert('please enter the name"');
$('#name').focus();
}
});
$('#removeAll').click(function() {
localStorage.setItem('woman', '[]'); ///localStorage.setItem('woman', JSON.stringify([]));
displayName();
});
displayName();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="formular">
<label for="name">Enter the name</label>
<input type="text" id="name" required />
<label for="section">Gender</label>
<select name="selectSection" id="section" required>
<option value="">---</option>
<option value="man" id="man">man</option>
<option value="woman" id="woman">woman</option>
</select>
<input type="submit" value="add" />
</form>
<button id="removeAll">Remove</button>
<div id="man_div">
<h1>man:</h1>
<ul id="list"></ul>
</div>
<div id="woman_div">
<h1>woman:</h1>
<ul id="list_2"></ul>
</div>
I made a number of changes to your script, do note that as I am solving your problem, I removed the 'x' function on click because it is too verbose to read while solving your problem, do add it back later, and make sure you remove from the correct localStorage.
$(document).ready(function () {
function displayName() {
//Separate the local storage into man and woman keys
let manSafeNameVal = localStorage.getItem('man');
let manSafeName;
let womanSafeNameVal = localStorage.getItem('woman');
let womanSafeName
if (manSafeNameVal) {
manSafeName = JSON.parse(manSafeNameVal);
} else {
manSafeName = [];
}
if (womanSafeNameVal) {
womanSafeName = JSON.parse(womanSafeNameVal);
} else {
womanSafeName = [];
}
//find list
//Use list and list_2 to display
let manUl = $('#list');
let womanUl = $('#list_2');
manUl.empty(); //.html('')
womanUl.empty();
//list for man
$.each(manSafeName, function (key, name) {
let nameLi = $('<li></li>');
nameLi.text(name);
//do add back your 'x' remove here, because it is too verbose to read when I am trying to read the code
manUl.append(nameLi);
});
//list for woman
$.each(womanSafeName, function (key, name) {
let nameLi = $('<li></li>');
nameLi.text(name);
//Also here, the 'x' for woman list
womanUl.append(nameLi);
});
}
$('#formular').submit(function (e) {
e.preventDefault();
let zadaneJmeno = $('#name').val();
//get the selected gender, either man or woman
let gender = $('#section').val();
console.log(gender);
console.log(zadaneJmeno);
if (zadaneJmeno && gender !== "") {
//safe into the localStorage of selected gender
let safeNameVal = localStorage.getItem(gender);
let safeName;
if (safeNameVal) {
safeName = JSON.parse(safeNameVal);
} else {
safeName = [];
}
safeName.push(zadaneJmeno);
localStorage.setItem(gender, JSON.stringify(safeName));/// ["Tom"]
//list
displayName();
$('#name').val('');
} else {
// alert
alert('please enter the name"');
$('#name').focus();
}
});
$('#removeAll').click(function () {
localStorage.setItem('woman', '[]'); ///localStorage.setItem('woman', JSON.stringify([]));
displayName();
});
displayName();
});
const katText = document.getElementById('txtKategorie');
const oText=document.querySelector('input[homework="homework"]');
// selektor tlačítka uložit úkol
const oBttn=document.querySelector('input[type="submit"]');
// selektor tlačítka na odstranění všech úkolů z kategorie
const oDelete=document.querySelector('button#removeAll');
const createlist=function(){
let parent=document.getElementById('lists');
Object.keys(localStorage).forEach(function (key) {
let category = key;
let div = document.createElement('div');
div.id = category;
let h1 = document.createElement('h1');
h1.textContent = category;
let ul = document.createElement('ul');
div.appendChild(h1);
div.appendChild(ul);
div.onclick = oznacDiv;
parent.appendChild(div);
});
parent.querySelectorAll('div').forEach( div=>{
div.addEventListener('click',function(e){
// odstranění určité položky
if( e.target!=e.currentTarget && e.target.tagName=='A') deleteitem( e );
});
// při načtení stránky načíst úkoly z localStorage a vytvoření listu
// podmmínka -- pokud není úložiště prázdné
let store=div.id;
if( localStorage.getItem(store)!=null )JSON.parse( localStorage.getItem( store ) ).forEach( homework=>{
addlistitem(homework,store);
})
});
}
//na klik oznaci div
function oznacDiv() {
if (oBttn.disabled) oBttn.disabled = false;
document.querySelectorAll('div.active').forEach(div => {
div.classList.remove('active')
});
document.querySelector('div#' + this.id).classList.add('active')
}
const clearstoreitems=function(category){
localStorage.setItem( category, JSON.stringify([]) );
document.querySelector( 'div#' + category ).querySelector('ul').innerHTML='';
};
const deleteitem=function(e){
let parent=e.target.parentNode;
let homework=parent.dataset.homework;
let category=parent.dataset.category;
parent.parentNode.removeChild(parent);
let data=JSON.parse(localStorage.getItem(category));
if( data!=null )data.splice(data.indexOf(homework),1);
localStorage.setItem(category,JSON.stringify(data));
};
const addlistitem=function(homework,category){
let p=document.createElement('button');
p.innerHTML=' Uprava';
p.onclick =function(){
editWorking(li);
}
let a=document.createElement('a');
a.href='#';
a.innerHTML=' Hotovo';
let li=document.createElement('li');
li.value=homework;
li.textContent=homework;
li.dataset.homework=homework;
li.dataset.category=category;
li.appendChild( a );
li.appendChild(p);
document.querySelector( 'div#' + category ).querySelector('ul').appendChild( li );
};
function editWorking(e){
let editValue = prompt('Přejete si upravit úkol?', e.firstChild.nodeValue);
e.firstChild.nodeValue = editValue;
let parent=e.parentNode;
let homework=parent.dataset.homework;
let category=parent.dataset.category;
addlistitem(editValue,category);
addstoreitem(editValue,category);
}
const addstoreitem=function(homework,category){
let data=localStorage.getItem( category );
if( data!=null ){
let json=JSON.parse( data );
json.push(homework);
data=JSON.stringify(json);
}
else
{
data=JSON.stringify([homework]);
}
localStorage.setItem( category, data );
};
//prida novej div s kategorii a poznamkou
const addNewItemList = function () {
let parent = document.getElementById('lists');
let category = katText.value;
let div = document.createElement('div');
div.id = category;
let h1 = document.createElement('h1');
h1.textContent = category;
let ul = document.createElement('ul');
div.appendChild(h1);
div.appendChild(ul);
div.onclick = oznacDiv;
parent.appendChild(div);
parent.querySelectorAll('div').forEach(div => {
div.addEventListener('click', function (e) {
// odstranění určité položky
if (e.target != e.currentTarget && e.target.tagName == 'A') deleteitem(e);
});
// při načtení stránky načíst úkoly z localStorage a vytvoření listu
// podmmínka -- pokud není úložiště prázdné
let store = div.id;
if (localStorage.getItem(store) != null) JSON.parse(localStorage.getItem(store)).forEach(homework => {
addlistitem(homework, store);
})
});
}
oBttn.addEventListener('click',function(e){
e.preventDefault();
if (oText.value != '') {
if (katText.value != '') {
if (document.querySelector('div#' + katText.value) == null) {
addNewItemList()
}
addlistitem(oText.value, katText.value);
addstoreitem(oText.value, katText.value);
oText.value = '';
return true;
} else {
alert('Zadejte kategorii prosím...');
}
} else {
alert('Zadejte úkol prosím...');
}
});
// vymazat, resetovat pole
oDelete.addEventListener('click', function (e) {
document.querySelectorAll('div.active').forEach(div => {
//clearstoreitems(document.querySelectorAll('div.active').id);
clearstoreitems(div.id);
//div.classList.remove('active')
});
});
createlist();
#charset "UTF-8";
/* CSS Document */
#import url('https://fonts.googleapis.com/css2?family=Poppins:wght#100;200;300;400;500;600;700;800;900&display=swap');
*{
padding: 100;
margin: 100;
box-sizing: border-box;
font-family: 'Poppins', sans-serif;
}
/**styly pro tělo celé aplikace **/
body{
background: rgb(131,58,180);
background: linear-gradient(90deg, rgba(131,58,180,1) 0%, rgba(253,29,29,1) 50%, rgba(252,176,69,1) 100%);
/* background: linear-gradient(139deg, rgba(193,62,62,1) 0%, rgba(230,179,50,1) 100%);
background-image: url("pozadi.png");*/
overflow-x: hidden;
background-repeat: no-repeat;
background-size: cover;
background-position: center;
background-attachment: fixed;
height: 100%;
}
.weather{
width: 100%;
margin: 20px;
padding: 30px;
}
/** pomohla jsem si tady https://the-echoplex.net/flexyboxes/ **/
/**
.flex-container {
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
-webkit-flex-wrap: nowrap;
-ms-flex-wrap: nowrap;
flex-wrap: nowrap;
-webkit-justify-content: flex-start;
-ms-flex-pack: start;
justify-content: flex-start;
-webkit-align-content: center;
-ms-flex-line-pack: center;
align-content: center;
-webkit-align-items: center;
-ms-flex-align: center;
align-items: center;
}
.flex-item:nth-child(1) {
-webkit-order: 0;
-ms-flex-order: 0;
order: 0;
-webkit-flex: 0 1 auto;
-ms-flex: 0 1 auto;
flex: 0 1 auto;
-webkit-align-self: auto;
-ms-flex-item-align: auto;
align-self: auto;
}
.flex-item:nth-child(2) {
-webkit-order: 0;
-ms-flex-order: 0;
order: 0;
-webkit-flex: 0 100 auto;
-ms-flex: 0 100 auto;
flex: 0 100 auto;
-webkit-align-self: auto;
-ms-flex-item-align: auto;
align-self: auto;
}
**/
/**nadpis aplikace **/
#nadpis {
/** margin: auto;
width: 50%;
padding: 5px; **/
text-align: center;
font-size: 40px;
}
.predpoved {
/** width: 30%; **/
border-radius: 15px 50px;
border:4px solid white;
background: black;
-webkit-box-shadow: 7px 8px 6px 0px rgba(0,0,0,0.52);
box-shadow: 7px 8px 6px 0px rgba(0,0,0,0.52);
margin:0 auto;
height: 10%;
width:60%;
padding: 0 auto;
}
.nadpis_1{
font-size: 50px;
color:white;
font:bold;
}
label{
color:white;
font:oblique;
text-transform:inherit;
}
#lists > div{
padding:1rem;
margin:1rem auto;
border-radius: 15px 50px;
border:4px solid white;
margin-left: 30px;
margin-right: 30px;
-webkit-box-shadow: 7px 8px 6px 0px rgba(0,0,0,0.52);
box-shadow: 7px 8px 6px 0px rgba(0,0,0,0.52);
}
.active{
background: linear-gradient(90deg, rgba(252,176,69,1) 0%, rgba(253,29,29,1) 50%, rgba(131,58,180,1)100%);
}
h1{
text-transform:capitalize;
color:white;
}
ul{
list-style: square;
}
ul li{
color:white;
margin-top: 40px;
font-size: 20px;
}
ul a {
color:white;
font:oblique;
padding: 10px;
margin:10px;
margin-left:100px;
border-radius: 15px ;
border:1px solid white;
text-decoration: none;
text-transform: uppercase;
}
ul a:hover {
color:white;
font:oblique;
background:rgba(252,176,69,1);
padding: 10px;
margin:10px;
margin-left:100px;
border:1px solid white;
text-decoration: none;
text-transform: uppercase;
}
form{
color: white;
padding: 20px;
width: 600px;
margin: 0 auto;
height: auto;
}
#removeAll{
color:white;
font:oblique;
background: black;
border-radius: 15px ;
border:1px solid white;
text-decoration: none;
text-transform: uppercase;
margin: 0 auto;
height: auto;
padding:10px;
margin-left: 30px;
margin-right: 30px;
}
#removeAll:hover {
color:white;
font:oblique;
background: red;
border:1px solid white;
text-decoration: none;
text-transform: uppercase;
padding:10px;
margin: 0 auto;
height: auto;
margin-left: 30px;
margin-right: 30px;
}
#refresh{
color:white;
font:oblique;
background: black;
border-radius: 15px ;
border:1px solid white;
text-decoration: none;
text-transform: uppercase;
margin: 0 auto;
height: auto;
padding: 10px;
}
#refresh:hover {
color:white;
font:oblique;
background: red;
border:1px solid white;
text-decoration: none;
text-transform: uppercase;
padding:10px;
margin: 0 auto;
height: auto;
}
#safe{
color:white;
font:oblique;
background: black;
border-radius: 15px ;
border:1px solid white;
text-decoration: none;
text-transform: uppercase;
margin: 0 auto;
height: auto;
padding: 10px;
}
#safe:hover {
color:white;
font:oblique;
background: red;
border:1px solid white;
text-decoration: none;
text-transform: uppercase;
padding:10px;
margin: 0 auto;
height: auto;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Deadline</title>
<link rel="stylesheet" href="style.css">
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<div class="flex-container">
<div id="nadpis">
<h1>Deadline</h1>
<form>
<label for="txtHomework">Your homework.. </label>
<input type="text" id="txtHomework" homework="homework" required />
<label for="txtKategorie">Category</label>
<input type="text" id="txtKategorie" kategorie="valKategorie" required />
<!--<select name="selectSection" required>
<option selected hidden disabled>---</option>
<option value="škola">Škola</option>
<option value="Práce">Práce</option>
<option value="Doma">Doma</option>
<option value="Jiné">Jiné</option>
</select>-->
<!--</label>-->
<!-- tlačítko uložit je nedostupné dokud nevybereme kategorii a nezapíšeme úkol -->
<input id ="safe" type="submit" value="Uložit" />
</form>
<div id="lists"></div>
<button id="removeAll">Vyčistit kategorii</button>
I know you already have a solution but I offer an alternative, in vanilla Javascript rather than jQuery, that splits the names according to gender - assigns them to individual areas in localStorage based upon gender and has the functionality to remove individual items from the store. Any items stored in any of the generated stores will be used to populate the HTML lists on page load. I don't use jQuery which is why I wrote this in plain js - no doubt you can cherrypick things from it that might be useful - I hope that it is useful anyway.
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Gender splitter</title>
<style>
#lists > div{
padding:1rem;
margin:1rem auto;
border:1px dotted gray;
}
.active{
background:whitesmoke
}
h1{text-transform:capitalize}
</style>
</head>
<body>
<form>
<label>Enter the name
<input type='text' name='name' required />
</label>
<label>Gender
<select name='selectSection' required>
<option selected hidden disabled>---
<option value='male'>Male
<option value='female'>Female
<option value='teapot'>Teapot
<option value='crocodile'>Crocodile
</select>
</label>
<!-- initially disabled to prevent adding when no gender is selected -->
<input type='submit' value='add' disabled />
</form>
<button id='removeAll'>Remove</button>
<div id='lists'></div>
<script>
const oSelect=document.querySelector('select[name="selectSection"]');
const oText=document.querySelector('input[name="name"]');
const oBttn=document.querySelector('input[type="submit"]');
const oDelete=document.querySelector('button#removeAll');
// generate the necessary HTML nodes to display names/genders based
// upon the options in the select menu.
const createlist=function(){
let parent=document.getElementById('lists');
oSelect.querySelectorAll('option').forEach( option=>{
if( option.value !== oSelect.childNodes[1].value ){
let gender=option.value;
let div=document.createElement('div');
div.id=gender;
let h1=document.createElement('h1');
h1.textContent=gender;
let ul=document.createElement('ul');
div.appendChild(h1);
div.appendChild(ul);
parent.appendChild( div );
}
});
parent.querySelectorAll('div').forEach( div=>{
div.addEventListener('click',function(e){
// delete specific item from the store
if( e.target!=e.currentTarget && e.target.tagName=='A') deleteitem( e );
});
// load any names from the store on page load and recreate the lists
let store=div.id;
if( localStorage.getItem(store)!=null )JSON.parse( localStorage.getItem( store ) ).forEach( name=>{
addlistitem(name,store);
})
});
}
// erase store content by gender and clear html list display
const clearstoreitems=function(gender){
localStorage.setItem( gender, JSON.stringify([]) );
document.querySelector( 'div#' + gender ).querySelector('ul').innerHTML='';
};
// delete specific item from particular store
const deleteitem=function(e){
let parent=e.target.parentNode;
let name=parent.dataset.name;
let gender=parent.dataset.gender;
parent.parentNode.removeChild(parent);
let data=JSON.parse(localStorage.getItem(gender));
if( data!=null )data.splice(data.indexOf(name),1);
localStorage.setItem(gender,JSON.stringify(data));
};
// add new item to HTML list based upon gender
const addlistitem=function(name,gender){
let a=document.createElement('a');
a.href='#';
a.innerHTML='X';
let li=document.createElement('li');
li.value=name;
li.textContent=name;
li.dataset.name=name;
li.dataset.gender=gender;
li.appendChild( a );
document.querySelector( 'div#' + gender ).querySelector('ul').appendChild( li );
};
// add new name to the localStorage in gender specific named store
const addstoreitem=function(name,gender){
let data=localStorage.getItem( gender );
if( data!=null ){
let json=JSON.parse( data );
json.push(name);
data=JSON.stringify(json);
} else { data=JSON.stringify([name]); }
localStorage.setItem( gender, data );
};
// Add new item listener
oBttn.addEventListener('click',function(e){
e.preventDefault();
if( oText.value!='' ){
addlistitem(oText.value,oSelect.value);
addstoreitem(oText.value,oSelect.value);
oText.value='';
return true;
}
alert('Name please...');
});
oSelect.addEventListener('change',function(e){
// ensure the "Add" button is enabled
if( oBttn.disabled )oBttn.disabled=false;
document.querySelectorAll('div.active').forEach( div=>{
div.classList.remove('active')
});
// assign a class to visually identify which gender is selected
document.querySelector( 'div#' + this.value ).classList.add('active')
});
// erase this entire store - reset to empty array
oDelete.addEventListener('click',function(e){
clearstoreitems(oSelect.value);
});
createlist();
</script>
</body>
</html>
const addBtn = document.querySelector(".add");
const modal = document.querySelector(".modal__container");
const library = document.querySelector(".library__container");
const submitBook = document.querySelector(".add__book");
const deleteBtn = document.querySelector(".fas fa-trash-alt");
//Modal inputs
const modalTitle = document.querySelector("#title");
const modalAuthor = document.querySelector("#author");
const modalPages = document.querySelector("#pages");
const isRead = document.querySelector("#read-status");
//Toggle Modal
const hideModal = () => {
modal.style.display = "none";
};
const showModal = () => {
modal.style.display = "block";
const cancel = document.querySelector(".cancel");
cancel.addEventListener("click", (e) => {
e.preventDefault();
hideModal();
});
};
addBtn.addEventListener("click", showModal);
let myLibrary = [];
let index = 0;
function Book(title, author, pages, read) {
this.title = title,
this.author = author,
this.pages = pages,
this.read = read
}
submitBook.addEventListener("click", addBookToLibrary);
function addBookToLibrary(e) {
e.preventDefault();
let bookTitle = modalTitle.value;
let bookAuthor = modalAuthor.value;
let bookPages = modalPages.value;
let bookStatus = isRead.checked;
//Display error message if inputs are empty
if (bookTitle === "" || bookAuthor === "" || bookPages === "") {
const errorMessage = document.querySelector(".error__message--container");
hideModal();
errorMessage.style.display = "block";
const errorBtn = document.querySelector(".error-btn");
errorBtn.addEventListener("click", () => {
errorMessage.style.display = "none";
showModal();
})
} else {
let book = new Book(bookTitle, bookAuthor, bookPages, bookStatus);
myLibrary.push(book);
hideModal();
render();
}
}
function render() {
library.innerHTML = "";
for (let i = 0; i < myLibrary.length; i++) {
library.innerHTML +=
'<div class="book__container">' +
'<div class="book">' +
'<div class="title__content">' +
'<span class="main">Title : </span><span class="book__title">' +` ${myLibrary[i].title}`+'</span>' +
'</div>' +
'<div class="author__content">' +
'<span class="main">Author : </span><span class="book__author">'+` ${myLibrary[i].author}`+'</span>' +
'</div>' +
'<div class="pages__content">' +
'<span class="main">Pages : </span><span class="book__pages">'+` ${myLibrary[i].pages}`+'</span>' +
'</div>' +
'<div class="book__read-elements">' +
'<span class="book__read">I read it</span>' +
'<i class="fas fa-check"></i>' +
'<a href="#"><i class="fas fa-times"></i>' +
'<i class="fas fa-trash-alt"></i>' +
'</div>' +
'</div>' +
'</div>'
readStatus(myLibrary[i].checked)
}
modalTitle.value = "";
modalAuthor.value = "";
modalPages.value = "";
isRead.checked = false;
}
function readStatus(bookStatus) {
const bookStatusContainer = document.querySelector(".book__read");
if (bookStatus) {
bookStatusContainer.classList.add("yes");
bookStatusContainer.textContent = "I read it";
bookStatusContainer.style.color = "rgb(110, 176, 120)";
} else {
bookStatusContainer.classList.add("no");
bookStatusContainer.textContent = "I have not read it";
bookStatusContainer.style.color = "rgb(194, 89, 89)";
}
}
#import url('https://fonts.googleapis.com/css2?family=Poppins:wght#300;400;600&display=swap');
:root {
--light-gray: #dededef3;
--title-color: #333756;
--main-color: #c6c6c6f3;
}
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
font-family: 'Poppins', sans-serif;
background-color: var(--light-gray);
}
header {
text-align: center;
padding-top: 4rem;
color: var(--title-color);
text-transform: uppercase;
letter-spacing: 4px;
}
button {
margin: 1rem;
padding: 0.8rem 2rem;
font-size: 14px;
border-radius: 25px;
background: white;
color: #333756;
font-weight: 600;
border: none;
cursor: pointer;
transition: 0.6s all ease;
}
:focus {
/*outline: 1px solid white;*/
}
button:hover {
background: var(--title-color);
color: white;
}
.add__book:hover,
.cancel:hover {
background: var(--main-color);
color: var(--title-color)
}
.all,
.books__read,
.books__not-read {
border-radius: 0;
text-transform: uppercase;
letter-spacing: 0.1rem;
background: var(--light-gray);
border-bottom: 4px solid var(--title-color)
}
.library__container {
display: flex;
justify-content: center;
flex-wrap: wrap;
}
.book__container {
display: flex;
margin: 2rem 2rem;
}
.modal__container {
display: none;
position: fixed;
z-index: 4;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.4);
padding-top: 0px;
}
.book,
.modal {
padding: 2rem 2rem;
border-radius: 15px;
background: #333756;
line-height: 3rem;
}
.modal {
position: relative;
width: 50%;
margin: 0 auto;
margin-top: 8rem;
}
.modal__content {
display: flex;
flex-direction: column;
}
label {
color: white;
margin-right: 1rem;
}
input {
padding: 0.5rem;
font-size: 14px;
}
.book__read-elements {
display: flex;
justify-content: space-between;
}
.main,
i {
color: white;
pointer-events: none;
margin: 0.5rem;
}
.book__title,
.book__author,
.book__pages,
.book__read {
color: var(--main-color)
}
.error__message--container {
display: none;
position: fixed;
z-index: 4;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.4);
}
.error__message--modal {
position: relative;
margin: 0 auto;
margin-top: 10rem;
width:40%;
}
.error {
display: flex;
flex-direction: column;
align-items: center;
color: rgb(101, 3, 3);
font-size: 20px;
font-weight: bold;
background: rgb(189, 96, 96);
padding: 3rem 5rem;
border-radius: 10px;
}
.error-btn {
color: rgb(101, 3, 3);
font-weight: bold;
}
.error-btn:hover {
color: white;
background: rgb(101, 3, 3);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.1/css/all.min.css" integrity="sha256-2XFplPlrFClt0bIdPgpz8H7ojnk10H69xRqd9+uTShA=" crossorigin="anonymous" />
<link rel="stylesheet" href="styles.css">
<title>Library</title>
</head>
<body>
<header>
<h1>My Library</h1>
<button class="add">Add New Book</button>
<div class="buttons">
<button class="all">View All</button>
<button class="books__read">Read</button>
<button class="books__not-read">Not Read</button>
</div>
</header>
<div class="error__message--container">
<div class="error__message--modal">
<div class="error">
<p>Complete the form!</p>
<button class ="error-btn">Ok</button>
</div>
</div>
</div>
<!--Modal-->
<form class="modal__container">
<div class="modal">
<div class="modal__content">
<label for="">Title:</label>
<input type="text" id="title">
</div>
<div class="modal__content">
<label for="">Author:</label>
<input type="text" id="author">
</div>
<div class="modal__content">
<label for="">Pages:</label>
<input type="number" id="pages">
</div>
<div>
<label for="read-status">Check the box if you've read this book</label>
<input type="checkbox" id="read-status" value ="check">
</div>
<button class="add__book">Add</button>
<button class="cancel">Cancel</button>
</div>
</form>
<!--End of Modal-->
<div class="library__container"></div>
<script src="script.js"></script>
</body>
</html>
I'm new to OOP and I'm struggling.
I'm building a library where you can add a book with the title, author nr of pages and if you've read it or not. When I add the first book if I check the box it displays that to book is not read(which is false). When I add a new book the read functionality is not applied to that book at all. I have no idea how to fix it
In this function you are checking the status if isRead which is incorrect.
Do this
Call the readStatus function inside the for loop
Pass the current parameter readStatus(myLibrary[i].checked)
Modify readStatus as shown below
function readStatus(status) {
const bookReadStatus = document.querySelector(".book__read");
if (status) {
bookReadStatus.classList.add("yes");
bookReadStatus.textContent = "I read it";
bookReadStatus.style.color = "rgb(110, 176, 120)";
} else {
bookReadStatus.classList.add("no");
bookReadStatus.textContent = "I have not read it";
bookReadStatus.style.color = "rgb(194, 89, 89)";
}
}
I am a newbie in JS (level 0), and although I try to store all the variables of my practice in Local Storage, I am doing something wrong, because when reloading the page many functions (previously visible), now disappear in the reload.
SEE LIVE DEMO
Where is my errors...?
What am I doing wrong...?
Thanks in advance!
CSS
html{top:0;left:0;margin:0}body{top:0;margin:0;padding:0;color:#323232;width:100%;height:100%;line-height:1.5;font-family:'Roboto',serif}#container{width:500px;margin:0 auto}#container p{display:inline-block;margin-top:20px}#productos{display:none}.img-prod{display:inline-block;float:left;margin-right:10px}.img-prod img{width:100%;height:auto;max-width:70px;display:block;border:0}#comp-p1,#comp-p2,#comp-p3{width:120px;height:30px;margin-top:15px;background:green;padding:10px 0 5px;text-align:center;vertical-align:middle;color:#fff;cursor:pointer}.derecha{border:solid 1px #999;max-height:400px;width:350px;margin:0 auto;text-align:center;padding:10px 0;overflow-y:auto;float:right}#producto-1,#producto-2,#producto-3{display:inline-block;width:220px;padding:10px;float:left;text-align:left;font-size:.9em;margin-right:5px}#producto-1{background:green;color:#fff}#producto-2{background:#add8e6;color:#000}#producto-3{background:#666;color:#fff}.cont-p{display:inline-block;margin:7px auto;line-height:1}.bbp{display:inline-block;vertical-align:top;width:24px;height:24px;text-align:center;background:red;color:#fff;margin-left:5px;line-height:1.5;cursor:pointer}.cont-num{float:left;width:24px;height:24px;margin:20px 5px 0 20px;padding:4px 3px 3px;background:red;text-align:center;font-size:16px;font-family:Arial,sans-serif;color:#fff}#mostrar{display:none;width:100px;margin:70px 0 0;padding:10px;text-align:center;background:grey;color:#fff;cursor:pointer}.derecha input{width:0;height:0;border:none;visibility:hidden}#cont-resultado{text-align:center;width:110px;margin-top:70px;background:grey;padding:5px 10px 10px;color:#fff}#cont-resultado input{display:inline-block;margin:10px auto;background:#fff;color:#000;border:1px solid #000;padding:8px 0}#cont-resultado p{display:inline-block;text-decoration:none;color:#fff;background:grey;padding:8px 10px;cursor:pointer}#total{display:block;width:80px;text-align:center}
HTML
<div id="container">
<div id="productos">
<!-- ============================================== -->
<div id="cont-p1" class="cont-p">
<div id="producto-1">
<div class="img-prod"><img src="https://upload.wikimedia.org/wikipedia/commons/3/39/Lichtenstein_img_processing_test.png"> </div>cont-p1 cloned!<br><br>Input Value = 1</div>
<input class="add-prod" type="num" value="1">
<div class="bbp">X</div>
</div>
<!-- ============================================== -->
<div id="cont-p2" class="cont-p">
<div id="producto-2">
<div class="img-prod"><img src="https://upload.wikimedia.org/wikipedia/commons/3/39/Lichtenstein_img_processing_test.png"></div>
cont-p2 cloned!<br><br>Input Value = 1</div>
<input class="add-prod" type="num" value="1">
<div class="bbp">X</div>
</div>
<!-- ============================================== -->
<div id="cont-p3" class="cont-p">
<div id="producto-3">
<div class="img-prod"><img src="https://upload.wikimedia.org/wikipedia/commons/3/39/Lichtenstein_img_processing_test.png"></div>
cont-p3 cloned!<br><br>Input Value = 198</div>
<input class="add-prod" type="num" value="198">
<div class="bbp">X</div>
</div>
<!-- ============================================== -->
</div><!-- // productos -->
<div class="derecha"></div>
<div id="comp-p1" onClick="clickME();clickME2();">Clone 1</div>
<div id="comp-p2" onClick="clickME();clickME2();">Clone 2</div>
<div id="comp-p3" onClick="clickME();clickME2();">Clone 3</div>
<div class="cont-num" id="clicks">0</div>
<div class="cont-num" id="clicksdos">0</div>
<div id="cont-resultado">
<input name="total" id="total">
Total of sum
</div>
</div>
<!-- // container -->
<script>
// Script que suma y resta los clicks
var clicks = 0;
function clickME() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks
}
var clicksdos = 0;
function clickME2() {
clicksdos += 1;
document.getElementById("clicksdos").innerHTML = clicksdos;
if (clicksdos === 1) {
document.getElementById("cont-resultado").style.display = "block";
}
}
if (clicksdos === 0) {
document.getElementById("cont-resultado").style.display = "none";
}
function restar() {
if (clicks > 0) clicks -= 1;
document.getElementById("clicks").innerHTML = clicks;
}
function restardos() {
if (clicksdos > 0) clicksdos -= 1;
document.getElementById("clicksdos").innerHTML = clicksdos;
if (clicksdos === 0) {
document.getElementById("cont-resultado").style.display = "none";
}
}
</script>
SCRIPT
// Script for clone the div´s
$(document).ready(function() {
$("#comp-p1").click(function() {
$("#cont-p1").clone().appendTo(".derecha");
localStorage.setItem("html",document.getElementsByClassName("derecha")[0].innerHTML); // New
displaySuma();
});
// =============
$("#comp-p2").click(function() {
$("#cont-p2").clone().appendTo(".derecha");
localStorage.setItem("html",document.getElementsByClassName("derecha")[0].innerHTML); // New
displaySuma();
});
// =============
$("#comp-p3").click(function() {
$("#cont-p3").clone().appendTo(".derecha");
localStorage.setItem("html",document.getElementsByClassName("derecha")[0].innerHTML); // New
displaySuma();
});
});
const getParent = (match, node) => (node.matches(match)) ? node : getParent(match, node.parentNode);
// Deal with remove
document.addEventListener('click', (event) => {
let target = event.target;
if (target.matches('.bbp')) {
restar();
restardos();
getParent('.derecha', target).removeChild(target.parentNode);
localStorage.setItem("html",document.getElementsByClassName("derecha")[0].innerHTML); // New
displaySuma();
}
})
// New Script for sum inputs
const displaySuma = () => document.getElementById("total").value = suma();
const suma = function() {
let x = Array.from(document.querySelectorAll(".derecha div .add-prod"));
let sum = 0;
for (var i = 0; i < x.length; i++) {
sum += parseFloat(x[i].value);
}
console.log(sum);
return sum;
localStorage.setItem("html",document.getElementsByClassName("derecha")[0].innerHTML); // New
}
//console.log(suma());
document.getElementById("total").value = suma();
// New
if ((localStorage.getItem("clicks")!=null) && (localStorage.getItem("clicksdos")!=null))
{
clicks=parseInt(localStorage.getItem("clicks"));
clicksdos=parseInt(localStorage.getItem("clicksdos"));
document.getElementById("clicks").innerHTML=clicks;
document.getElementById("clicksdos").innerHTML=clicksdos;
}
if (localStorage.getItem("html")!=null)
{
document.getElementsByClassName("derecha")[0].innerHTML=localStorage.getItem("html")
}
//});
Here is a version using localStorage unfortunately snippets does not allow use of localStorage.
Because of this, here is a version of the code running in jsFiddle
let clicks = 0;
let clicksdos = 0;
const safeInt = (key) => {
let value = parseInt(getValue(key));
return (isNaN(value) || value < 0) ? 0 : value;
}
// This loads our clicks from the LocalStorage
const loadClicks = () => {
clicks = safeInt('clicks');
clicksdos = safeInt('clicksdos');
}
const loadHTML = () => {
return getValue('html', '');
}
const loadFromStorage = () => {
let html = loadHTML();
if (html !== '') {
loadClicks();
}
displayClicks();
document.querySelector(".derecha").innerHTML = html;
}
// Display the clicks on the screen
const displayClicks = () => {
clicks = (clicks === NaN) ? 0 : clicks;
clicksdos = (clicksdos === NaN) ? 0 : clicksdos;
document.querySelector('#clicks').innerHTML = clicks;
document.querySelector('#clicksdos').innerHTML = clicksdos;
// Hide / Show Result
let display = (clicks > 0) ? 'block' : 'none';
document.querySelector('#cont-resultado').style.display = display;
}
const adjustClicks = (value) => {
clicks += value;
clicksdos += value;
storeValue('clicks', clicks);
storeValue('clicksdos', clicksdos);
displayClicks();
}
const addClick = () => adjustClicks(1);
const removeClick = () => adjustClicks(-1);
// Manage localStorage
const storeValue = (key, value) => (localStorage) ? localStorage.setItem(key, value) : '';
const getValue = (key, defaultValue) => (localStorage) ? localStorage.getItem(key) : defaultValue;
const storeHTML = () => storeValue("html", document.getElementsByClassName("derecha")[0].innerHTML);
// Add a node to the Derecha
const addToDerecha = (nodeId) => {
let node = document.querySelector(`#${nodeId}`);
document.querySelector('.derecha').appendChild(node.cloneNode(true));
storeHTML();
displaySuma();
};
// Monitor ALL click events
document.addEventListener('click', (event) => {
let target = event.target;
// Add
if (target.matches('.comp-clone')) {
addClick();
addToDerecha(event.target.dataset.clone);
}
// Remove
if (target.matches('.bbp')) {
removeClick();
getParent('.derecha', target).removeChild(target.parentNode);
storeHTML();
displaySuma();
}
});
// This is just a helper function.
const getParent = (match, node) => (node.matches(match)) ? node : getParent(match, node.parentNode);
// New Script for sum inputs
const displaySuma = () => document.getElementById("total").value = suma();
const suma = function() {
return Array.from(document.querySelectorAll(".derecha div .add-prod"))
.reduce((a, v) => a + parseFloat(v.value), 0);
}
// Code to run when the document loads.
document.addEventListener('DOMContentLoaded', () => {
if (localStorage) {
loadFromStorage();
}
displaySuma();
});
body {
margin: 0 auto;
color: #323232;
width: 100%;
height: 100%;
line-height: 1.5;
font-family: 'Roboto', serif
}
#container {
width: 500px;
margin: 0 auto
}
#container p {
display: inline-block;
margin-top: 20px
}
span {
font-weight: bold;
text-decoration: underline
}
#productos {
display: none
}
.img-prod {
display: inline-block;
float: left;
background: #000;
margin-right: 10px
}
.img-prod img {
width: 100%;
height: auto;
max-width: 70px;
display: block;
border: 0
}
#comp-p1,
#comp-p2,
#comp-p3 {
width: 120px;
height: 30px;
margin-top: 15px;
background: green;
padding: 10px 0 5px;
text-align: center;
vertical-align: middle;
color: #fff;
cursor: pointer
}
.derecha {
border: solid 1px #999;
max-height: 400px;
width: 350px;
margin: 0 auto;
text-align: center;
padding: 10px 0;
overflow-y: auto;
float: right
}
#producto-1,
#producto-2,
#producto-3 {
display: inline-block;
width: 220px;
padding: 10px;
float: left;
text-align: left;
font-size: .9em;
margin-right: 5px
}
#producto-1 {
background: green;
color: #fff
}
#producto-2 {
background: #add8e6;
color: #000
}
#producto-3 {
background: #666;
color: #fff
}
.cont-p {
display: inline-block;
margin: 7px auto;
line-height: 1
}
.bbp {
display: inline-block;
float: right;
width: 24px;
height: 24px;
text-align: center;
background: red;
color: #fff;
margin-left: 5px;
line-height: 1.5;
cursor: pointer
}
.cont-num {
float: left;
width: 24px;
height: 24px;
margin: 20px 5px 0 18px;
padding: 4px 3px 3px;
background: red;
text-align: center;
font-size: 16px;
font-family: Arial, sans-serif;
color: #fff
}
#mostrar {
display: none
}
#mostrar {
width: 100px;
margin: 70px 0 0;
padding: 10px;
text-align: center;
background: grey;
color: #fff;
cursor: pointer
}
/* ==== Style of Sume ==== */
.derecha input {
width: 40px;
display: block;
margin: 0 auto 10px 0;
padding: 2px 0;
background: #f2f2f2;
border: none;
border: 1px solid #000;
text-align: center
}
#cont-resultado {
text-align: center;
width: 110px;
margin-top: 70px;
background: grey;
padding: 5px 10px 10px;
color: #fff
}
#cont-resultado input {
display: inline-block;
margin: 10px auto;
background: #fff;
color: #000;
border: 1px solid #000;
padding: 8px 0
}
#cont-resultado p {
display: inline-block;
text-decoration: none;
color: #fff;
background: grey;
padding: 8px 10px;
cursor: pointer
}
#total {
display: block;
width: 80px;
text-align: center
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="container">
<div id="productos">
<!-- =============== -->
<div id="cont-p1" class="cont-p">
<div id="producto-1">
<div class="img-prod"><img src="https://upload.wikimedia.org/wikipedia/commons/3/39/Lichtenstein_img_processing_test.png"> </div>cont-p1 cloned!<br><br>Input Value = 1</div>
<input class="add-prod" type="num" value="1">
<div class="bbp">X</div>
</div>
<!-- =============== -->
<div id="cont-p2" class="cont-p">
<div id="producto-2">
<div class="img-prod"><img src="https://upload.wikimedia.org/wikipedia/commons/3/39/Lichtenstein_img_processing_test.png"></div>
cont-p2 cloned!<br><br>Input Value = 1</div>
<input class="add-prod" type="num" value="1">
<div class="bbp">X</div>
</div>
<!-- =============== -->
<div id="cont-p3" class="cont-p">
<div id="producto-3">
<div class="img-prod"><img src="https://upload.wikimedia.org/wikipedia/commons/3/39/Lichtenstein_img_processing_test.png"></div>
cont-p3 cloned!<br><br>Input Value = 198</div>
<input class="add-prod" type="num" value="198">
<div class="bbp">X</div>
</div>
<!-- =============== -->
</div>
<!-- // productos -->
<div class="derecha"></div>
<div id="comp-p1" data-clone="cont-p1" class="comp-clone">Clone 1</div>
<div id="comp-p2" data-clone="cont-p2" class="comp-clone">Clone 2</div>
<div id="comp-p3" data-clone="cont-p3" class="comp-clone">Clone 3</div>
<div class="cont-num" id="clicks">0</div>
<div class="cont-num" id="clicksdos">0</div>
<div id="cont-resultado">
<span>RESULT:</span><br>
<input name="total" id="total">
<br>Is the sum of the cloned divs
<!--<p id='sumup'>Ver total</p>-->
</div>
<p><span>NOTE:</span><br>Here we are looking for only the cloned inputs can be sumed (and see the result in the box color gray).<br><br>The problem is that the current script does not apply a sume of the cloned inputs only... it adds ALL the inputs presents
in the html...<br><br>So (1), how do you sum only the cloned inputs, ignoring those that are outside...?<br><br>And (2) also, how to subtract from the total result all the cloned divs that are deleted...?</p>
</div>
<!-- // container -->
<script src="script.js"></script>
</body>
</html>
I am trying to learn JavaScript; this is what I made for a test. My problem is that I want to count my table rows, but when I remove a table name it should adapt the table row numbers.
Is there someone who can tell me how I should or could do this? If you have a comment about my coding please give it as I want to learn as much as possible.
var count = 0;
var btn = document.getElementById("btn");
var table = document.getElementById("table");
var removeRowBtn = document.getElementById("removeRowBtn");
var tableNr = document.getElementById("tableNr");
// input fields Variable
var firstName = document.getElementsByName("firstName")[0];
var lastName = document.getElementsByName("lastName")[0];
var Age = document.getElementsByName("Age")[0];
var Country = document.getElementsByName("Country")[0];
var AgeCheck = document.myForm.Age.valueOf;
// this function is checking if the input fields have the recuired data in it other wise it give's a error.
function validate() {
// first name field check + error
if( document.myForm.firstName.value == "" ) {
alert( "Please provide your first name!" );
document.myForm.firstName.focus() ;
return false;
}
// last name field check + error message
if( document.myForm.lastName.value == "" ) {
alert( "Please provide your last name!" );
document.myForm.lastName.focus() ;
return false;
}
// age field check + error message
if( isNaN(document.myForm.Age.value) || document.myForm.Age.value < 1 || document.myForm.Age.value > 100 ){
alert( "Please provide your age!");
return false;
}
// country select list check + error message
if( document.myForm.Country.value == "chooseCountry" ) {
alert( "Please provide your country!" );
return false;
}
// if evry thing is true return a value of true
return true;
}
function tableFunction() {
// if validate is true go
if( validate() ){
// count to see how many row's there are added
count++;
// making a new Row
var newRow = document.createElement("tr");
// adding the tow to the Table
table.appendChild(newRow);
// adding a class and a count-id to the Row
newRow.className = "tableRow";
newRow.setAttribute ("id", count);
// adding 4 td to the tr
for(i = 0; i < 5; i++ ){
var newData = document.createElement("td");
newRow.appendChild(newData);
newData.className = "tableData";
// check the td count and place data in.
if(i == 0){
table.getElementsByTagName("tr")[count].getElementsByTagName("td")[i].innerHTML = count;
} else if (i == 1) {
table.getElementsByTagName("tr")[count].getElementsByTagName("td")[i].innerHTML = firstName.value;
} else if (i == 2) {
table.getElementsByTagName("tr")[count].getElementsByTagName("td")[i].innerHTML = lastName.value;
} else if (i == 3) {
table.getElementsByTagName("tr")[count].getElementsByTagName("td")[i].innerHTML = Age.value;
} else if (i == 4){
table.getElementsByTagName("tr")[count].getElementsByTagName("td")[i].innerHTML = Country.value;
}
}
}
}
function removeTableRow(){
i = tableNr.value;
// if there is no table number filled in show a error alert
if( i == "" ) {
alert( "Please provide a table number!" );
tableNr.focus() ;
return false;
}
// find the chosen array
var row = table.getElementsByTagName("tr")[i];
// if the number is not in the row show error alert that it issen't in the table
if( row == undefined ){
alert( "this row number is not in the table" );
return false;
}
row.remove(row.selectedIndex);
}
removeRowBtn.onclick = function() {removeTableRow()};
btn.onclick = function(){ tableFunction()};
body{
background: white;
}
img{
height: 100%;
display: block;
margin: 0 auto;
}
p{
text-align: center;
}
.container{
width: 100%;
max-width: 600px;
border-radius: 2px;
margin: 0 auto;
margin-top: 8vh;
background: lightgray;
box-shadow: 0px 4px 4px darkgray;
}
table{
width: 100%;
text-align: center;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
/* Button */
.btn {
display: inline-block;
margin: 1em auto;
font-weight: 100;
padding: 1em 1.25em;
text-align: center;
width: 100% ;
border-radius: 1px;
position: relative;
z-index: 0;
cursor: pointer;
border: none;
background: #0c84e4;
box-shadow: 0px 1px 1px #063e6b;
color: #FFFFFF;
}
:focus {
outline: -webkit-focus-ring-color auto 0px;
}
.btn.red{
background:red;
width: 100%;
}
/* input field style's */
input[type=text] {
width: calc(25% - 8px);
padding: 12px 20px 12px 5px;
margin: 8px 4px;
box-sizing: border-box;
float: left;
border: none;
border-bottom: 2px solid #536DFE;
text-align: center;
background: transparent;
}
input:focus{
outline: none;
color: black;
}
::-webkit-input-placeholder{
color:black;
font: helvetica 12px bold ;
text-align: center;
}
select{
width: calc(25% - 8px);
padding: 12px 20px 12px 5px;
margin: 8px 4px;
box-sizing: border-box;
float: left;
border: none;
border-bottom: 2px solid #536DFE;
text-align: center;
background: transparent;
height: 39px;
border-radius: 0px !important;
}
<!DOCTYPE html>
<html>
<head>
<title>Inzend Opgave H5</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- style sheets -->
<link href="style.css" rel="stylesheet" type="text/css" >
</head>
<body>
<div id="wrapper">
<section class="container">
<form id="personInfo" name="myForm">
<table>
<tbody id="table">
<tr>
<td>nr.</td>
<td>First Name</td>
<td>Last Name</td>
<td>Age</td>
<td>Country</td>
</tr>
</tbody>
</table>
<input type="text" name="firstName" placeholder="firstName">
<input type="text" name="lastName" placeholder="lastName">
<input type="text" name="Age" placeholder="Age">
<select name="Country">
<option value="choose a country">Kies een land</option>
<option value="Nederland">NL</option>
<option value="Belgie">BE</option>
<option value="Duitsland">DE</option>
</select>
<input type="button" name="button" id="btn" class="btn" value="Add the input fields to the table">
<p>To remove a table number fill in the input field with the <br> number of the table and click remove table row</p>
<input type="button" name="button" id="removeRowBtn" class="btn" value="remove table row" style="width: 75%;">
<input type="text" name="TableNr" id="tableNr" placeholder="table nr.">
</form>
</section>
</div>
<!-- java-scripts -->
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.js"></script>
<script type="text/javascript">
var cw = $('.container').width();
$('.container').css({
'height': cw + 'px'
});
</script>
</body>
</html>
Change
row.remove(row.selectedIndex);
to
row.remove(row.selectedIndex);
var rows = document.querySelectorAll("#table tr");
for (var i = 1; i < rows.length; i++) { rows[i].cells[0].innerText = i; }