console out checked radio buttons - javascript

Im trying to console out a radio button with JS in order to see the value of the checked button. the Js seems to be without syntax error, but it returns undefined:
this is the HTML:
const firstName = document.querySelector('#FirstName');
const lastName = document.querySelector('#LastName');
const email = document.querySelector('#email');
const comments = document.querySelector('#comments');
let meeting1 = document.querySelector('#meetingtype1');
let meeting2 = document.querySelector('#meetingtype2');
let meeting3 = document.querySelector('#meetingtype3');
let meeting4 = document.querySelector('#meetingtype4');
let meeting;
if (meeting1.checked) {
meeting = meeting1.value;
console.log(meeting = "1");
} else if (meeting2.checked) {
meeting = meeting2.value;
console.log(meeting = "2")
} else if (meeting3.checked) {
meeting = meeting3.value;
console.log(meeting = "3")
} else if (meeting4.checked) {
meeting = meeting4.value;
console.log(meeting = "4")
}
const submitform = document.querySelector('#submitform');
submitform.addEventListener('click', function() {
console.log(` Name: ${firstName.value}, Last Name: ${lastName.value}, Email: ${email.value}, Comment: ${comments.value} Type of meeting: ${meeting}`);
});
<fieldset>
<legend>Would you like to meet for?</legend>
<label><input type="radio" id="meetingtype1" name=meetingtype value="coffee" > A coffee</label>
<label><input type="radio" id="meetingtype2" name=meetingtype value="zoom"> A zoom meeting</label>
<label><input type="radio" id="meetingtype3" name=meetingtype value="drive"> A drive to Eilat</label>
<label><input type="radio" id="meetingtype4" name=meetingtype value="chef"> A chef meal</label>
<button id="submitform" type="submit">Submit</button>
thank you very much!

Since you want to check the value/log it onto your console when you are going to click onto your button, make sure to use your if-else-statement inside of the EventListener and not outside of the function. If you write the if-else-statement in your way, it will be executed when the page loads the first time.
To print out your current value of the selected meeting change your JavaScript Code to this. I modified your provided code.
let meeting1 = document.querySelector('#meetingtype1');
let meeting2 = document.querySelector('#meetingtype2');
let meeting3 = document.querySelector('#meetingtype3');
let meeting4 = document.querySelector('#meetingtype4');
let meeting;
const submitform = document.querySelector('#submitform');
submitform.addEventListener('click', function () {
if (meeting1.checked){
meeting = meeting1.value;
} else if (meeting2.checked){
meeting = meeting2.value;
} else if (meeting3.checked){
meeting = meeting3.value;
} else if (meeting4.checked){
meeting = meeting4.value;
}
console.log(`Type of meeting: ${meeting}`);
});

Related

The Edit and delete button are not working?

I am very new to javascript I have been working on a to-do app for the last couple of days, for a coding Bootcamp project and I have updated my coding format so that it is easier to read than what I had before but now the edit and delete functions are not working.
I set up the id and elements for the tasks.
const createTask = () => {
const id = createId()
const task = elements.input.value;
const date = elements.cal.value;
if(!task && !date) return alert("Please fill in task and select date");
if(!task) return alert("Please fill in task");
if(!date) return alert("Please select date");
const tasks = document.createElement("div");
tasks.innerHTML = `
<button class = "sort" data-id="${id}">Sort</button>
<div class="task" date-id = "${id}">
<div class="content">
<input type ="checkbox" class="tick">
<input type ="text" class = text id = "text" data-id="" readonly>${task}
<label class = "due-date" for ="text">${date}</label>
<input type ="date" class = date id = "date">
</div>
<div class = "actions">
<button class="edit" data-id="${id}">Edit</button>
<button class="delete" data-id="${id}">Delet</button>
</div>
</div>
`
elements.list.appendChild(tasks)
return tasks
}
I set up the event listener for the submit, edit and delete. The add list button works fine but the edit and delete button are not working.
elements.list.addEventListener('click',event => {
const {target} = event;
const {id} = target.dataset
const task = id ? document.querySelector('[data-id="${id}"]'): null
const type = {
edit: event.target.classList.contains('edit'),
delete: event.target.classList.contains('delete'),
}
const isFromSaveLabel = target.innerText.toLowerCase() === 'save'
if(tasks && type.edit && isFromSaveLabel){
const text = task.querySelector('text')
target.innerText = 'Edit'
text.addAttribute('readonly')
return
}
if(tasks && type.edit){
const text = task.querySelector('text')
target.innerText = 'Save'
text.removeAttribute('readonly')
text.focus()
return
}
if(tasks && type.delete){
return
}
});
const submitHandler = (event) =>{
event.preventDefault();
createTask();
}
elements.form.addEventListener("submit", submitHandler);
Is it possible for someone to help me to have the following implemented in my code that does the following:
Sort the list alphabetically
can edit the calendar as well when you edit the list you want to change
save the user list using local storage.
It is just those 3 things that need to be added. I code almost every single day for hours and javascript is a bit challenging for me and I do struggle sometimes and this project is due on Friday.

How to automatically select checkboxes if user input in "wall_amount" exceeds 3

I would like my program to automatically select all checkboxes (Specifically "Side 1, Side 2, Side 3 and Side 4") if the wall_amount input is above 3. How would this be done?
I have tried this on javascript lines 10-12. Thanks
HTML
<label for="wall_amount">Number of Walls</label>
<input type="number" value="1" min="1" max="4" step="1" id="wall_amount" name="wall_amount"></input>
<div>
Please choose where you want the walls placed
<label for="wall_side1">Side 1</label>
<input type="checkbox" id="wall_side1" name="wall_side1"></input>
<div style="display: inlineblock;">
<label for="wall_side2">Side 2</label>
<input type="checkbox" id="wall_side2" name="wall_side2"></input>
<img class="img2" src="images/reference.png" alt="Bouncy Castle">
<label for="wall_side3">Side 3</label>
<input type="checkbox" id="wall_side3" name="wall_side3"></input>
</div>
<label for="wall_side4">Side 4</label>
<input type="checkbox" id="wall_side4" name="wall_side4"></input>
</div>
Javascript
var base_length = Number(document.getElementById("base_length").value);
var base_width = Number(document.getElementById("base_width").value);
var walltype = Number(document.getElementById("walltype").value);
var checkbox_side1 = document.getElementById("wall_side1");
var checkbox_side2 = document.getElementById("wall_side2");
var checkbox_side3 = document.getElementById("wall_side3");
var checkbox_side4 = document.getElementById("wall_side4");
var wall_amount = Number(document.getElementById("wall_amount").value);
$("input:checkbox").click(function() {
let max = $("#wall_amount").val();
var bol = $("input:checkbox:checked").length >= max;
$("input:checkbox").not(":checked").attr("disabled", bol);
});
$("wall_amount").on('keyup', function () {
$('checkbox_side1').prop('checked', +$(this).val() > 3);
});
You can use the function setAttribute to check checkboxes. For example, this code (based on your example) will check your element with the id wall_side1.
checkbox_side1.setAttribute("checked", true)
Anyway, try adding this to your code as a function. Then add a conditional statement that runs the function every time your variable exceeds a certain amount.
I am still relatively new at answering questions so I hope this helps!
const checkboxes = [
"wall_side1",
"wall_side2",
"wall_side3",
"wall_side4"
].map((id) => document.getElementById(id));
const amountInput = document.getElementById("wall_amount");
amountInput.addEventListener("change", (event) => {
const value = parseInt(event.target.value || 0);
if (value === 4) {
checkboxes.forEach(
checkbox => {
checkbox.disabled = true;
checkbox.checked = true;
}
);
} else {
checkboxes.forEach(
checkbox => {
checkbox.disabled = false;
}
);
}
});

How can i add or update products and prices in my list?

Pretty new to javascript, i want to add and update my list but it doesn't work.
I tried adding following code but it didn't work
Product.prototype.addProduct = function() {
var elol = document.getElementById("lijst");
var nieuwNaam = document.createElement("li");
nieuwNaam.textContent= this.naam;
elol.appendChild(nieuwNaam);
var nieuwPrijs = document.createElement("li");
nieuwPrijs.textContent= this.prijs;
elol.appendChild(nieuwPrijs);
}
Product.prototype.getProducten = function() {
return this.naam + "(€ " + this.prijs +")";
}
This is the document i want wish would work propperly
<!DOCTYPE html>
<html>
<head>
<script src="oefwinkel.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function() {
winkel.addProduct("Potlood", 10);
VulLijst();
var elBtn = document.getElementById("btn");
elBtn.onclick = VoegProductToe;
});
function VulLijst() {
var elol = document.getElementById("lijst");
var producten = winkel.getProducten("</li><li>");
if (producten.length > 0) {
elol.innerHTML = "<li>" + producten + "</li>";
} else {
elol.innerHTML = "";
}
}
function VoegProductToe() {
var naam = document.getElementById("txtNaam").value;
var prijs = document.getElementById("txtPrijs").value;
winkel.addProduct(naam, prijs);
VulLijst();
}
function Product(naam, prijs) {
this.naam = naam;
this.prijs = prijs;
}
</script>
</head>
<body>
<div><label for="txtNaam">Naam:</label>
<input type="text" id="txtNaam" /></div>
<div><label for="txtPrijs">Prijs:</label>
<input type="number" id="txtPrijs" /></div>
<input type="button" id="btn" value="Toevoegen/Updaten" />
<ol id="lijst">
</ol>
</body>
</html>
There is no list output how do i correct this?..
I really can't find the solution, what did i miss.. huh?
You had a few things missing,
The HTML code.
The winkel object was undefined.
The VulLijst function was doing nothing... because addProduct was taking care of this already.
You are relying on the instance fields (this.naam and this.prijs), but what you want to do is pass in method parameters (external variables).
As for updating, you will need to store a list of Products, clear the child elements of lijst, and re-add the items that represent the list.
Note: One thing I am confused about is why you named your class—that represents a list—Product, when it should really be an Inventory that allows you to ADD Product objects.
Code
// Uncaught ReferenceError: winkel is not defined
var winkel = new Product();
function Product(naam, prijs) {
this.naam = naam;
this.prijs = prijs;
}
Product.prototype.addProduct = function(naam, prijs) {
naam = naam || this.naam; // Default or instance field
prijs = prijs || this.prijs; // Default or instance field
console.log(naam, prijs);
var elol = document.getElementById("lijst");
var nieuwNaam = document.createElement("li");
nieuwNaam.textContent = naam;
elol.appendChild(nieuwNaam);
var nieuwPrijs = document.createElement("li");
nieuwPrijs.textContent = prijs;
elol.appendChild(nieuwPrijs);
}
Product.prototype.getProducten = function(naam, prijs) {
naam = naam || this.naam; // Default or instance field
prijs = prijs || this.prijs; // Default or instance field
return naam + " (€ " + prijs + ")";
}
document.addEventListener("DOMContentLoaded", function() {
winkel.addProduct("Potlood", 10); // Why are you adding a product to a product?
var elBtn = document.getElementById("btn");
elBtn.onclick = VoegProductToe;
});
function VoegProductToe() {
var naam = document.getElementById("txtNaam").value;
var prijs = document.getElementById("txtPrijs").value;
winkel.addProduct(naam, prijs);
}
label { font-weight: bold; }
<label>Product</label>
<input id="txtNaam" value="Something" />
<input id="txtPrijs"value="1.99" />
<button id="btn">Add</button>
<br/>
<ul id="lijst"></ul>
Explained
I will openly admit, I'm not 100% sure what you're trying to do, I assume that's due to a language barrier my side though, I'm not sure of the natural language that you use on a daily basis, i.e. some of the variable names seem unclear to me, but that's my problem, not yours! :)
Anyway, I used some guess work to figure out what you're trying to achieve, and I assumed that you're simply trying to have some sort of product list where each product has a name and a price attached to it?
You want to be able to add a product to the list, based on two input fields, then some button to add to/update that product list.
I've broken up the code into a couple of simple functions, with this solution you can add/remove as many functions, classes or whatever you want. In this answer you can clearly see that there's some render function, and some onUpdate function, I just went with these generic names for the sake of simplicity.
If you have any issues with this solution, please provide as much feedback as possible! I hope that it's been of some help one way or another.
// A simple product list.
const ProductList = () => {
const products = [];
let el = null;
// What you wish to return, aka an object...
return {
addProduct: (name, price) => {
products.push({
name: name,
price: price
});
onUpdate();
render(el, products);
},
setRoot: root => {
el = root;
},
// removeFromList, etc...
};
};
// A simple on update function.
const onUpdate = () => {
console.clear();
console.log('Update!');
};
// A 'simple' render function.
const render = (el, products) => {
if (el == null) return;
const template = obj => `<li>${obj.name} €${obj.price}</li>`;
let html = '';
products.forEach(product => html += template(product));
el.innerHTML = html;
};
// A function to dispatch some event(s).
const dispatchEvents = products => {
const btn = document.getElementById("btn");
const price = document.getElementById("price");
const name = document.getElementById("name");
// Just an example.
const isValid = () => {
if (price.value != '' && name.value != '') return true;
return false;
};
// Handle the on click event.
btn.onclick = () => {
if (isValid()) {
products.addProduct(name.value, price.value);
name.value = '';
price.value = '';
}
};
};
// A simple dom ready function.
const ready = () => {
const products = ProductList();
products.setRoot(document.getElementById("productList"));
products.addProduct('Demo', 10);
products.addProduct('Other', 19.99);
dispatchEvents(products);
};
document.addEventListener("DOMContentLoaded", ready);
<div>
<label for="name">name:</label>
<input type="text" id="name" />
</div>
<div>
<label for="price">Prijs:</label>
<input type="number" id="price" />
</div>
<input type="button" id="btn" value="Update" />
<ol id="productList">
</ol>

Java Script error handling

I have a function where I check my two (or one) input fileds if they are empty i want to let's say print alert in window but if they have vaules i want to run else but in my case alert is not popping up and if i want to submit those two fileds with data it is ok pushing it and doing alll stuff in else but whole browser is reloading. I was trying to add prevent.Default() but not working. Or return false
UPDATE: I made some changes and know when input is empty alert is popping up, but when i colse it it is still realoding whole page, same thing if else is executed all browser is reloading
let pushBtn = document.getElementById('push-btn');
pushBtn.addEventListener('click', pushData);
function pushData() {
let deviceVal = document.getElementById('device').value;
let powerVal = document.getElementById('power').value;
if (deviceVal != '' || powerVal != '') {
let list = document.getElementById('list-group')
let button = document.createElement('button');
let ul = document.createElement('ul');
let liFirst = document.createElement('li');
let liSecond = document.createElement('li');
let liThird = document.createElement('li');
button.classList.add("list-group-item");
ul.classList.add("desc");
liFirst.classList.add("t-desc");
liSecond.classList.add("t-desc2");
liThird.classList.add("t-desc3");
liFirst.textContent = deviceVal;
liSecond.textContent = powerVal;
liThird.innerHTML = `<label class="switch">
<input type="checkbox">
<span class="slider round"></span>
</label>`
modal.style.display = 'none';
ul.append(liFirst);
ul.append(liSecond);
ul.append(liThird);
button.append(ul);
list.prepend(button);
} else {
alert('aaa');
return false
}
}
<input type="text" name="device" required />
Job done, no JavaScript needed.
* But you should use a submit event on the form, not a click event on the button.
Specifically for your question, you want the alert to trigger if either input is blank, but you're testing if either one isn't blank. Use == instead of !=.
ok got it!
function pushData(e) {
let deviceVal = document.getElementById('device').value;
let powerVal = document.getElementById('power').value;
e.preventDefault()
if (deviceVal != '' || powerVal != '') {
let list = document.getElementById('list-group')
let button = document.createElement('button');
let ul = document.createElement('ul');
let liFirst = document.createElement('li');
let liSecond = document.createElement('li');
let liThird = document.createElement('li');
button.classList.add("list-group-item");
ul.classList.add("desc");
liFirst.classList.add("t-desc");
liSecond.classList.add("t-desc2");
liThird.classList.add("t-desc3");
liFirst.textContent = deviceVal;
liSecond.textContent = powerVal;
liThird.innerHTML = `<label class="switch">
<input type="checkbox">
<span class="slider round"></span>
</label>`
modal.style.display = 'none';
ul.append(liFirst);
ul.append(liSecond);
ul.append(liThird);
button.append(ul);
list.prepend(button);
} else {
alert('aaa');
}
}
You can log to console before the "if" statement and inspect deviceVal/powerVal values, or use built-in debbuger in browser.
function pushData() {
console.log(deviceVal)
console.log(powerVal)
if (deviceVal != '' || powerVal != '') {
alert('aaa');
} else {..}
}

How to edit and update data in local storage?

I've been researching for hours and asked a number of times in stack overflow, but the answers did not help or I don't understand at all (user made use of jquery and php as part of solution which I do not know how to use)
Here are my codes (currentuser-will only show when user is logged in)
var currentUser=userList;
document.addEventListener("DOMContentLoaded",loadUserData);
function loadUserData() {
currentUser = localStorage.getItem("currentUser");
if(currentUser!=null) {
currentUser = JSON.parse(currentUser);
document.getElementById('username').value = currentUser.username;
document.getElementById('name').value = currentUser.name;
document.getElementById('password').value = currentUser.password;
document.getElementById('email').value = currentUser.email;
console.log(currentUser.username);
console.log(currentUser.name);
console.log(currentUser.password);
console.log(currentUser.email);
}
}
My codes to add users as objects into an array when they sign up for an account:
var userList;
document.addEventListener("DOMContentLoaded", loadUserList);
function loadUserList(){
if(localStorage.getItem("userList")===null) {
userList = [] ;
} else {
userList = JSON.parse(localStorage.getItem('userList'));
}
}
function saveUserToStorage(){
var u=document.getElementById("username").value;
var n=document.getElementById("name").value;
var p=document.getElementById("password").value;
var e=document.getElementById("email").value;
var user={"username":u,"name":n,"password":p,"email":e};
localStorage["user"]=JSON.stringify(user);
userList.push(user);
localStorage.setItem('userList',JSON.stringify(userList));
}
When I log in, it would direct me to the edit profile page and display data in the form which the user had entered when signing up.
What I NEED right now is just to change the local storage data by filling in the form. Just like editing it through the Inspect Element, just that it's being edited through the edit profile form. How do i achieve this?
Please help me. Would appreciate solutions without jquery/php
Sample of local storage:
Before editing
{"username":"alice66","name":"alice tan","password":"123","email":"abc#mail.com"}
After editing (through edit profile page)
{"username":"ben66","name":"ben ong","password":"qwerty","email":"xyz#mail.com"}
What would be the correct function to do so?
I tried the following function but it did not work:
var updatedUser=currentUser;
document.addEventListener("DOMContentLoaded",saveChanges);
function saveChanges() {
updatedUser = localStorage.getItem("updatedUser");
updatedUser = JSON.parse(updatedUser);
var u = document.getElementById("username").value = updatedUser.username;
var n = document.getElementById("name").value = updatedUser.name;
var p1 = document.getElementById("password1").value = updatedUSer.password1;
var p2 = document.getElementById("password2").value = updatedUser.password2;
var e = document.getElementById("email").value = updatedUser.email;
updatedUser={"username":u,"name":n,"password1":p1,"password2":p2,"email":e};
updatedUser.push(updatedUser);
localStorage.setItem('updatedUser',JSON.stringify(updatedUser));
}
It is rather simple
https://jsfiddle.net/ft3ur0cw/5/
<input placeholder="name" id="name"><br/>
<input placeholder="nausernameme" id="username"><br/>
<input placeholder="password" id="password"><br/>
<input placeholder="email" id="email"><br/><br/>
<button id="save" >save</button>
<br/><br/>
<input placeholder="name_saved" id="name_saved"><br/>
<input placeholder="nausernameme_saved" id="username_saved"><br/>
<input placeholder="password_saved" id="password_saved"><br/>
<input placeholder="email_saved" id="email_saved"><br/><br/>
function load_user(){
var userdata = localStorage.getItem("userdata");
if(typeof userdata === undefined || userdata === null){
userdata = JSON.stringify({username:"",name:"",password:"",email:""});
localStorage.setItem("userdata",userdata);
}
return JSON.parse(userdata);
}
function save_user(username , name, password, email){
userdata = JSON.stringify({username:username,name:name,password:password,email:email});
localStorage.setItem("userdata",userdata);
return userdata;
}
document.getElementById('save').addEventListener("click",function(){
save_user(
document.getElementById('username').value,
document.getElementById('name').value,
document.getElementById('password').value,
document.getElementById('email').value
);
userdata = load_user();
document.getElementById('username_saved').value = userdata.username;
document.getElementById('name_saved').value = userdata.name;
document.getElementById('password_saved').value = userdata.password;
document.getElementById('email_saved').value = userdata.email;
});
userdata = load_user();
document.getElementById('username_saved').value = userdata.username;
document.getElementById('name_saved').value = userdata.name;
document.getElementById('password_saved').value = userdata.password;
document.getElementById('email_saved').value = userdata.email;
this is pretty much how it goes.
EDIT:
better example demonstrating the use of the functions

Categories