I'm new to Javascript, and I want to swap these two options when the exchange button is clicked Page
HTML
<div class="form-group col-4">
<button type="button" class="btn bg-dark text-white" id="exchange" style="margin-top: 23px; margin-left: 10px;">
<i class="fa fa-exchange" aria-hidden="true"></i>
</button>
</div>
Javascript
function swap() {
let inp = document.getElementById("inputCurrency").value;
let out = document.getElementById("outputCurrency").value;
document.getElementById("inputCurrency").value = out;
document.getElementById("outputCurrency").value = inp;
}
let amountInput = document.getElementById("amount");
let inputCurrency = document.getElementById("inputCurrency");
let outputCurrency = document.getElementById("outputCurrency");
let convertButton = document.getElementById('convertButton');
convertButton.addEventListener("click",convertCurrency);
let exchangeButton = document.getElementById("exchange");
exchangeButton.addEventListener("click",swap());
You need remove function call in addEventListener, it contains only function name
exchangeButton.addEventListener("click",swap);
function swap() {
let inp = document.getElementById("inputCurrency").value;
let out = document.getElementById("outputCurrency").value;
document.getElementById("inputCurrency").value = out;
document.getElementById("outputCurrency").value = inp;
}
let amountInput = document.getElementById("amount");
let inputCurrency = document.getElementById("inputCurrency");
let outputCurrency = document.getElementById("outputCurrency");
let convertButton = document.getElementById('convertButton');
//convertButton.addEventListener("click",convertCurrency);
let exchangeButton = document.getElementById("exchange");
exchangeButton.addEventListener("click",swap);
<select id="inputCurrency">
<option value="1">USD</option>
<option value="2">KRW</option>
</select>
<select id="outputCurrency">
<option value="1">USD</option>
<option value="2">KRW</option>
</select>
<input type="text" id="amount"/>
<div class="form-group col-4">
<button type="button" class="btn bg-dark text-white" id="exchange" style="margin-top: 23px; margin-left: 10px;"> Exchange
<i class="fa fa-exchange" aria-hidden="true"></i>
</button>
</div>
<button id="convertButton">Convert</button>
addEventListener needs a function for second parameter. Add a callback function that calls swap() function.
exchangeButton.addEventListener("click", e => swap());
Related
I just started learning javascript few months ago. Recently i've been struggling to make this code work, but i end up messing up everything.
i want to make the reset button to clear user inputs?
Ive done several modification, but i couldn't still make it work. i dont know where i got it wrong.
Please i'll appreciate if anyone can assist me with this.
<div class=" DTRloading__form" style="display: block;">
<div class="form-container">
<div class="info">
</div>
<form class="form-inline">
<div class="form-group w-5 ">
<label for="red">Red Phase:</label>
<input type="number" class="form-control formInline" id="red" style="width: 80px">
</div>
<div class="form-group">
<label for="yellow">Yellow Phase:</label>
<input type="number" class="form-control formInline" id="yellow" style="width: 80px">
</div>
<div class="form-group">
<label for="blue">Blue Phase:</label>
<input type="number" class="form-control formInline" id="blue" style="width: 80px">
</div>
<div class="form-group">
<label for="neutral">Neutral:</label>
<input type="number" class="form-control formInline" id="neutral" style="width: 80px">
</div>
</form>
<label for="inputKVA" class="sr-only">DTR CAPACITY(Amp)</label>
<input type="number" id="inputKVA" class="form-control load" placeholder="DTR CAPACITY (KVA) *" required>
<button id="btnStart3" style="margin-top: 8px" class="btn btn2 btn-lg btn-primary btn-block ">Calculate</button>
</div>
<div class="output">
<h5 class="b-display">DTR Full Load Current is:</h5>
<div id="flA" class="form-control bill"></div>
<h5 class="b-display">The percentage Loading of this DTR is:</h5>
<div id="outputLoading" class="form-control bill"></div>
<!-- <div id="outputSum" class="form-control bill"></div>-->
<button id="btnRefresh3" class="btn btn2 btn-lg btn-primary btn-block">Reset</button>
</div>
</div>
<script>
document.getElementById("btnStart3").addEventListener('click', doCalc);
function doCalc() {
// Assign user inputs to variables
let x = parseFloat(document.querySelector("#red").value);
let y = parseFloat(document.querySelector("#yellow").value);
let z = parseFloat(document.querySelector("#blue").value);
let n = parseFloat(document.querySelector("#neutral").value);
const capacity = document.querySelector("#inputKVA");
const output2 = document.querySelector("#outputLoading");
const output3 = document.querySelector("#flA");
const start3 = document.getElementById("btnStart3");
const refresh3 = document.getElementById("btnRefresh3");
// // Call the average function
getAverage(x,y,z,n);
}
function getAverage(x,y,z,n) {
// Calculate the average
let average = ((((x + y + z + n) / 3) / (capacity.value * 1.391) )* 100);
// Display result to user
console.log(average);
outputLoading.innerHTML = average.toFixed(0) + "%";
//
}
const capacity = document.querySelector("#inputKVA");
function calculate(e) {
console.log(e);
e.preventDefault();
console.log("btnStart3 clicked");
var totalfLA = ((capacity.value * 1000) / (1.7321 * 415));
console.log(totalfLA);
flA.innerHTML = totalfLA.toFixed(1) + "A";
}
function emptyInput() {
console.log("emptied!");
outputKVA.innerHTML = "";
flA.innerHTML = "";
x.value = "";
y.value = "";
z.value = "";
n.value = "";
capacity.value = "";
output2.value = "";
output3.value = "";
}
btnStart3.addEventListener("click", calculate);
refresh3.addEventListener("click", emptyInput);
</script>
You can try in html with below button type as well.
<input type="reset" value="Reset">
If you want reset form from javascript then
document.getElementById("your-form-id").reset();
Change
1. <form class="form-inline">
2. refresh3.addEventListener("click", emptyInput);
to
1. <form class="form-inline" id="form">
2. document.getElementById("btnRefresh3").addEventListener("click", emptyInput);
3. function emptyInput() {
document.getElementById("form").reset();
}
I am currently building and invoice creator app as to practice javascript.
My goal is that when the user presses the "remove" button, only the clicked item will be removed from the list.
const theForm = document.getElementById('the-form');
const taskInput = document.getElementById('task-input');
const renderItem = document.querySelector('.render');
const selectOption = document.getElementById('amount');
const totalSum = document.getElementById('total-sum');
let totalAmount = 0;
theForm.addEventListener('submit', function(e) {
e.preventDefault();
totalAmount += parseInt(selectOption.value);
renderItem.innerHTML += `
<div class="render-item">
<div class="left-side">
<h2>${taskInput.value}</h2>
<button class='remove'>Remove</button>
</div>
<h2><span>$</span>${selectOption.value}</h2>
</div>
`;
totalSum.textContent = `$${totalAmount}`;
taskInput.value = '';
selectOption.value = '10';
const removeItem = document.querySelectorAll('.render-item');
removeItem.forEach((item) => {
item.addEventListener('click', function() {
renderItem.innerHTML = '';
totalAmount = 0;
totalSum.textContent = '';
});
});
});
<div class="outer-container">
<header>
<h1>Invoice creator</h1>
<p>Thanks for choosing RazCorp, LLC!</p>
</header>
<main class="inner-container">
<section class="form-enter">
<form id="the-form">
<input type="text" id="task-input" name="task-input" placeholder="Enter task" required />
<div class="amount-container">
<label for="amount">$</label>
<select name="amount" id="amount">
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="50">50</option>
</select>
</div>
<button id="submit-btn" class="submit" type="submit">+</button>
</form>
</section>
<section class="display">
<div class="task-total">
<h3>TASK</h3>
<h3>TOTAL</h3>
</div>
<div class="render"></div>
</section>
<section class="final-amount">
<div class="final-left">
<h3>NOTES</h3>
<p>We accept cash, credit card, or PayPal</p>
</div>
<div class="final-right">
<h3>TOTAL AMOUNT</h3>
<h1 id="total-sum"></h1>
</div>
</section>
<button id="send-invoice" class="send-invoice">
<span><i class="fa-solid fa-envelope"></i></span>Send invoice
</button>
</main>
</div>
First I am creating the Html through javascript and then I would like to remove it.
Right now when I press remove, every new created redenerItem is deleted and not just the one being clicked.
Any help appreciated :)
Because you have a single element that you're adding all of the entries to, when you press the remove button and it clears that single element, it clears all of the entries. What you probably want is a system that stores an array of all the items in the list, then selectively removing them. You might be able to use this:
const theForm = document.getElementById('the-form');
const taskInput = document.getElementById('task-input');
const selectOption = document.getElementById('amount');
const totalSum = document.getElementById('total-sum');
const renderItems = document.querySelector('.render');
const listItems = [];
let totalAmount = 0;
theForm.addEventListener('submit', function (e) {
e.preventDefault();
totalAmount += parseInt(selectOption.value);
//The Array.push method returns the new length of the array that we can use to get the item position
let itemPos = listItems.push(document.createElement('div')) - 1;
listItems[itemPos].innerHTML = `
<div class="left-side">
<h2>${taskInput.value}</h2>
<button class='remove' onclick='removeItem(${itemPos}, ${selectOption.value})'>Remove</button>
</div>
<h2><span>$</span>${selectOption.value}</h2>
`;
renderItems.appendChild(listItems[itemPos]);
totalSum.textContent = `$${totalAmount}`;
taskInput.value = '';
selectOption.value = '10';
});
//Move the remove item functionality to a new function
function removeItem(index, value) {
listItems[index].remove(); //Remove the element from the DOM
listItems.splice(index, 1); //Remove the element from the array
totalAmount -= value;
totalSum.textContent = `$${totalAmount}`;
}
<div class="outer-container">
<header>
<h1>Invoice creator</h1>
<p>Thanks for choosing RazCorp, LLC!</p>
</header>
<main class="inner-container">
<section class="form-enter">
<form id="the-form">
<input type="text" id="task-input" name="task-input" placeholder="Enter task" required />
<div class="amount-container">
<label for="amount">$</label>
<select name="amount" id="amount">
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="50">50</option>
</select>
</div>
<button id="submit-btn" class="submit" type="submit">+</button>
</form>
</section>
<section class="display">
<div class="task-total">
<h3>TASK</h3>
<h3>TOTAL</h3>
</div>
<div class="render"></div>
</section>
<section class="final-amount">
<div class="final-left">
<h3>NOTES</h3>
<p>We accept cash, credit card, or PayPal</p>
</div>
<div class="final-right">
<h3>TOTAL AMOUNT</h3>
<h1 id="total-sum"></h1>
</div>
</section>
<button id="send-invoice" class="send-invoice">
<span><i class="fa-solid fa-envelope"></i></span>Send invoice
</button>
</main>
</div>
const theForm = document.getElementById('the-form');
const taskInput = document.getElementById('task-input');
const renderItem = document.querySelector('.render');
const selectOption = document.getElementById('amount');
const totalSum = document.getElementById('total-sum');
let totalAmount = 0;
theForm.addEventListener('submit', function(e) {
e.preventDefault();
totalAmount += parseInt(selectOption.value);
renderItem.innerHTML += `
<div class="render-item">
<div class="left-side">
<h2>${taskInput.value}</h2>
<button class='remove'>Remove</button>
</div>
<h2><span>$</span>${selectOption.value}</h2>
</div>
`;
totalSum.textContent = `$${totalAmount}`;
taskInput.value = '';
selectOption.value = '10';
const removeItem = document.querySelectorAll('.render-item');
removeItem.forEach((item) => {
item.addEventListener('click', function() {
this.remove();
/*totalAmount = 0;
totalSum.textContent = '';*/
});
});
});
<div class="outer-container">
<header>
<h1>Invoice creator</h1>
<p>Thanks for choosing RazCorp, LLC!</p>
</header>
<main class="inner-container">
<section class="form-enter">
<form id="the-form">
<input type="text" id="task-input" name="task-input" placeholder="Enter task" required />
<div class="amount-container">
<label for="amount">$</label>
<select name="amount" id="amount">
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="50">50</option>
</select>
</div>
<button id="submit-btn" class="submit" type="submit">+</button>
</form>
</section>
<section class="display">
<div class="task-total">
<h3>TASK</h3>
<h3>TOTAL</h3>
</div>
<div class="render"></div>
</section>
<section class="final-amount">
<div class="final-left">
<h3>NOTES</h3>
<p>We accept cash, credit card, or PayPal</p>
</div>
<div class="final-right">
<h3>TOTAL AMOUNT</h3>
<h1 id="total-sum"></h1>
</div>
</section>
<button id="send-invoice" class="send-invoice">
<span><i class="fa-solid fa-envelope"></i></span>Send invoice
</button>
</main>
</div>
your event listener is already on the render-item, so just remove the element clicked.
now you will have the problem to update the amount and the text of 0.
you should add a class for the amount of each render-item, actually the amount is after the span that's it. If you have a class "render-item-amount" it would be easier at each update to modify the total
I am trying to add the elements of a list called "taskList" made up of values I get from the input elements.
Can anyone please help me, I don't understand why the elements from the list are not showing.
var taskList = [];
var input = document.getElementById('takeInput');
var button = document.getElementById('addInput');
button.onclick = function(){
var nHTML = '';
var userEnteredText = input.value;
taskList.push(userEnteredText);
taskList.forEach(function(task){
nHTML += '<li>'+task+'</li>';
});
document.getElementsByClassName('taskLists').innerHTML = '<ul>' + nHTML + '</ul>';
}
<div class="wrapper">
<header>To-Do List</header>
<div class="taskAdder">
<input id="takeInput" type="text" placeholder="Add your new To-Do">
<button id="addInput" class="button" type="button" >➕</button>
</div>
<div class="taskLists">
</div>
<div class="footer">
<span> You have <span class="pendingTasks"></span> tasks left </span>
<button type="button" class="button">Clear All</button>
</div>
</div>
I tried checking several times but nothing is updating in the HTML document
You shouldn't append to innerHTML, instead, use createElement to make the li, then set innerHTML of that new element to input.value and use appendChild to append it to the list
var input = document.getElementById('takeInput');
var button = document.getElementById('addInput');
var tlist = document.getElementsByClassName('taskLists')[0];
button.onclick = function(){
let e = document.createElement('li');
e.innerHTML = input.value
tlist.appendChild(e)
// Optionally, clear the input field to prevent double adding the same task
input.value = '';
}
<div class="wrapper">
<header>To-Do List</header>
<div class="taskAdder">
<input id="takeInput" type="text" placeholder="Add your new To-Do">
<button id="addInput" class="button" type="button" >➕</button>
</div>
<div class="taskLists">
</div>
<div class="footer">
<span> You have <span class="pendingTasks"></span> tasks left </span>
<button type="button" class="button">Clear All</button>
</div>
</div>
The main mistake was using .getElementsByClassName like it was one element only and not a list (don't ignore the s in elements!).
Anyway I slightly refactored your code to have better strategies for each of its goals and implemented also the logic for clearing the tasks list.
var taskList = [];
var input = document.getElementById('takeInput');
var buttonAdd = document.getElementById('addInput');
var buttonClear = document.getElementById('clearInput');
var tasksList = document.getElementById('tasksList');
buttonAdd.addEventListener('click', (event)=>{
addTask(input.value);
});
buttonClear.addEventListener('click', (event)=>{
tasksList = [];
document.querySelector('#tasksList ul').remove();
});
function addTask(value){
if(taskList.length == 0){
document.getElementById('tasksList').append( document.createElement('ul') );
}
taskList.push(value);
const newLI = document.createElement('li');
newLI.innerText = value;
document.querySelector('#tasksList ul').append(newLI);
}
<body>
<div class="wrapper">
<header>To-Do List</header>
<div class="taskAdder">
<input id="takeInput" type="text" placeholder="Add your new To-Do">
<button id="addInput" class="button" type="button">➕</button>
</div>
<div id="tasksList">
</div>
<div class="footer">
<span> You have <span class="pendingTasks"></span> tasks left </span>
<button id="clearInput" type="button" class="button">Clear All</button>
</div>
</div>
</body>
you just needed to use an ID on the tasklist.
getElementsByClassName needs an index, making your question a dupe of What do querySelectorAll and getElementsBy* methods return?:
document.getElementsByClassName('taskLists')[0].innerHTML
That said, here is a full version using recommended eventListener and IDs where relevant.
let tasks = [];
const taskList = document.getElementById('taskLists')
const input = document.getElementById('takeInput');
const add = document.getElementById('addInput');
const pendingTasks = document.getElementById('pendingTasks');
const clear = document.getElementById('clear');
const showTasks = () => {
taskList.innerHTML = `<ul>${tasks.map(task => `<li>${task}</li>`).join('')}</ul>`;
pendingTasks.textContent = `${tasks.length} task${tasks.length != 1 ? "s" : ""}`;
};
add.addEventListener('click', () => {
var userEnteredText = input.value;
tasks.push(userEnteredText);
showTasks();
});
clear.addEventListener('click', () => {
tasks = [];
showTasks();
});
taskList.addEventListener('click', (e) => {
const tgt = e.target.closest('li');
if (!tgt) return; // not a task
const task = tgt.textContent;
tgt.remove()
tasks = tasks.filter(currentTask => currentTask != task); // remove from list
showTasks()
});
showTasks(); //init
<div class="wrapper">
<header>To-Do List</header>
<div class="taskAdder">
<input id="takeInput" type="text" placeholder="Add your new To-Do">
<button id="addInput" class="button" type="button">➕</button>
</div>
<div id="taskLists"></div>
<div class="footer">
<span> You have <span id="pendingTasks"></span> left </span>
<button type="button" id="clear">Clear All</button>
</div>
</div>
I made a modal that is supposed to pop up when the user clicks the edit button. I hid the modal in CSS with display: none;
for some reason for the JS side I made a function that is linked to the edit button that when button is pressed the modal is changed to display: block;
What I did do was within the function renderList() I used the button onclick="editItem(event, ${i})" for the function editItem(event, i)
/*----Edit budget Entry----*/
function editItem(event, i){
alert("edit button clicked")
let mod = modal.style.display = "block";
console.log(mod)
}
I made a runable code so you can see.
/*----Storage key----*/
const BUDGETLIST_KEY = "user-key-entryList";
/*----Generate ID----*/
const createId = () => `${Math.floor(Math.random() * 10000)}${(new Date().getTime())}`;
/*----Get current Date----*/
function createdDate() {
let currentDate = new Date();
let day = String(currentDate.getDate()).padStart(2, '0');
let month = String(currentDate.getMonth() + 1).padStart(2, '0');
let year = currentDate.getFullYear();
currentDate = month + '/' + day + '/' + year;
return currentDate;
}
/*----Variable Objects----*/
const el = {
list: document.querySelector(".list"),
cashflow: document.querySelector("#cashflow"),
catagory: document.querySelector(".catagory"),
label: document.querySelector(".label"),
number: document.querySelector(".number"),
modal: document.querySelector(".modal"),
};
/*----Array with local Storage----*/
let budgetArray = [];
/*----Budget list Object----*/
function makeNewBudget() {
const data = {
id: createId(),
cashflowNew: el.cashflow.value,
catagoryNew: el.catagory.value,
labelNew: el.label.value,
dateNew: createdDate(),
numberNew: el.number.value,
};
return data;
}
/*----Render Budget List----*/
function renderList() {
el.list.innerHTML = budgetArray.map(function(data, i) {
return `<div class="entry">
<div class="list">
<button onclick="deleteItem(event, ${i})" class="Archive" data-id="${data.id}">
<img src="../resources/Images/archive.png" alt="Archive">
</button>
<button onclick="editItem(event, ${i})" class = "edit" data-id="${data.id}" class = "edit" data-id="${data.id}">
<img src="../resources/Images/edit.png" alt="Edit">
</button>
<div class="input" data-id="${data.id}"></div>
<label class="dateNew">${data.dateNew}</label>
<label class="cashflowNew">${data.cashflowNew}</label>
<label class="catagoryNew">${data.catagoryNew}</label>
<label class="labelNew">${data.labelNew}</label>
<label class="numberNew">${data.numberNew}</label>
</div>
</div>`;
});
}
/*----form validation----*/
let budgetButton = document.querySelector(".budget-button");
let label = document.querySelector(".label");
let num = document.querySelector(".number");
budgetButton.addEventListener("click", () => {
if (!label.value || !num.value) {
alert("please make sure all inputs are filled");
}
budgetArray.push(makeNewBudget())
renderList();
});
/*----Remove from array----*/
function deleteItem(event, i) {
budgetArray.splice(i, 1);
renderList();
}
/*----Close Modal----*/
let close = document.querySelector(".btn-close")
let xBtn = document.querySelector(".btn-secondary")
let modal = document.querySelector(".modal-content")
close.addEventListener('click', () => {
if (close) {
modal.style.display = "none"
}
});
xBtn.addEventListener('click', () => {
if (xBtn) {
modal.style.display = "none"
}
});
/*----Edit budget Entry----*/
function editItem(event, i) {
alert("edit button clicked")
let mod = modal.style.display = "block";
console.log(mod)
}
.modal {
display: block;
margin-top: 15rem;
display: none;
}
<!--Create budget-->
<div class="create-budget">
<form class="budget">
<input class="budget-button" type="button" value="Create your budget">
<select id="cashflow" name="income/expense" class="income/expense">
<option class="options" value="income">Income</option>
<option class="options" value="expense">Expense</option>
</select>
<select name="Catagory" class="catagory" value="Catagory">
<option class="options" value="House Hold">House Hold</option>
<option class="options" value="Car">Car</option>
<option class="options" value="entertainment">Entertainment</option>
<option class="options" value="investments">Investments</option>
<option class="options" value="business">Business</option>
<option class="options" value="savings">Savings</option>
</select>
<input class="label" type="text" placeholder="Example rent">
<input class="number" type="number" placeholder="0,0">
</form>
</div>
<div class="new-budet">
<div class="title">
<h5>Date</h5>
<h5>Income/Expenses</h5>
<h5>Catagory</h5>
<h5>Items</h5>
<h5>Amount</h5>
</div>
</div>
<div class="list"></div>
<div class="budget-update"></div>
<div class="modal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Want to make changes?</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form class="budget-update">
<select id="cashflow-update" name="income/expense" class="income/expense">
<option class="options-update" value="income">Income</option>
<option class="options-update" value="expense">Expense</option>
</select>
<select class="catagory-update" name="Catagory" value="Catagory">
<option class="options-update" value="House Hold">House Hold</option>
<option class="options-update" value="Car">Car</option>
<option class="options-update" value="entertainment">Entertainment</option>
<option class="options-update" value="investments">Investments</option>
<option class="options-update" value="business">Business</option>
<option class="options-update" value="savings">Savings</option>
</select>
<input class="label-update" type="text" placeholder="Example rent">
<input class="number-update" type="number" placeholder="0,0">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">
<img src="/resources/Images/Save-icon.png" alt="Save Icon">
</button>
</div>
</div>
</div>
</div>
Thanks to ethry answer it helped solve the problem. I forgot to add a variable for it
let modal= document.querySelector(".modal")
/*----Edit budget Entry----*/
function editItem(event, i){
modal.style.display = "block";
}
In order to use a variable, it needs to be defined. It looks like you accidentally left it undefined.
let modal = document.querySelector(".modal");
/*----Edit budget Entry----*/
function editItem(event, i){
modal.style.display = "block";
}
Or you could replace .querySelector(". with .getElementsByClassName(" and add [0] at the end.
More information about variables:
https://developer.mozilla.org/en-US/docs/Glossary/Variable
I have a project which is the note-taking website.
When someone adds a note it is stored in local storage in the form of an array and a Javascript function works which calls the stored element and runs for each on the elements.
Here is the Javascript code:
function showNote2() {
console.log("Show");
let note = localStorage.getItem("notes");
if(note == null){
noteData = []
// message.innerText = "Please Add a Note"
}
else{
noteData = JSON.parse(note);
};
let showBox = "";
noteData.forEach(function show(element, index) {
showBox += `<div class="noteCard my-2 mx-2 card" id="card4" style="width: 18rem;">
<select id="mySelect" class="clr-btn" style="text-align:center" onchange="change_color()">
<option id="bckgrnd-clr" value="white">Background Color</option>
<option id="red" value="Red">Red</option>
<option id="green" value="Green">Green</option>
<option id="blue" value="Blue">Blue</option>
</select>
<div class="card-body" id="card3">
<h5 class="cardtitle">Note
${index + 1}
</h5>
<p class="card-text">
${element}
</p>
<button id="${index}" onclick="deleteNote(this.id)" class="btn btn-primary">Delete Note</a>
</div>
</div> `
})
let showNote3 = document.getElementById("notes2");
if(noteData.length != 0){
showNote3.innerHTML = showBox;
}else{
showNote3.innerHTML = "Please add a Note"
}
}
In the above code, select gives us the option to choose a color for the note, now I want to add a function to onchange which can help me choose a different color for different notes.
The function I used was working only on the first-note and setting the color of all notes according to the selected option of first-note.
The color will be applied on class with card-body
I am building this for practice in Javascript. Any hints would be appreciated, as this is something new for me
Update:
This is the solution I applied after getting the idea from the comments.
function change_color(index) {
let note = localStorage.getItem("notes");
if(note != null ){
let colorApply = document.getElementById("card3")
let elm1 = document.getElementById(index)
let color = elm1.options[elm1.selectedIndex].value;
document.colorApply.style.backgroundColor = color;
}
else{
`Note is Empty`
}
Now this is the error i am getting at color
"Cannot read properties of null (reading 'options')"
Any help would be appreciated?
See the working snippet. :)
In your loop, change code like this:
let elm1 = document.getElementById(index)
to
let showNote3 = document.getElementById(`card${index}`);
let colorApply = document.getElementById(`card${index}`)
let elm1 = document.getElementById(`mySelect${index}`)
and in your HTML
`<div class="noteCard my-2 mx-2 card" id="card${index}" ...` />
`<select id=`mySelect${index}` class="clr-btn" style="text-align:center" onchange="change_color()">`
Also when you have the element, you do not need to use document
// -> document.colorApply.style.backgroundColor = color;
colorApply.style.backgroundColor = color;
Finally, you need to send the index of the note into your change_color function.
onchange="change_color(${index})"
function showNote2() {
console.log("Show");
let note = null // localStorage.getItem("notes");
if (note == null) {
noteData = ['My Note 1', 'My Note 2']
// message.innerText = "Please Add a Note"
} else {
noteData = JSON.parse(note);
};
let showBox = "";
noteData.forEach(function show(element, index) {
showBox += `
<div class="noteCard my-2 mx-2 card" id="card${index}" style="width: 18rem;">
<select id="mySelect${index}" class="clr-btn" style="text-align:center" onchange="change_color(${index})">
<option id="bckgrnd-clr" value="white">Background Color</option>
<option id="red" value="Red">Red</option>
<option id="green" value="Green">Green</option>
<option id="blue" value="Blue">Blue</option>
</select>
<div class="card-body" id="cardbody${index}">
<h5 class="cardtitle">Note ${index + 1}</h5>
<p class="card-text">
${element}
</p>
<button id="btn${index}" onclick="deleteNote(this.id)" class="btn btn-primary">Delete Note</a>
</div>
</div>
`
})
let showNote3 = document.getElementById("note");
if (noteData.length != 0) {
showNote3.innerHTML = showBox;
} else {
showNote3.innerHTML = "Please add a Note"
}
}
function change_color(index) {
let note = noteData[index] // localStorage.getItem("notes");
if (note != null) {
let colorApply = document.getElementById(`card${index}`)
let elm1 = document.getElementById(`mySelect${index}`)
let color = elm1.options[elm1.selectedIndex].value;
colorApply.style.backgroundColor = color;
} else {
console.log(`Note is Empty`)
}
}
showNote2()
<h1>Notes</h1>
<div id='note' />
<button onclick='note' />