On button click, query string missing last key-value pair - javascript

Objective
A user will make a set of choices about what gifts they want to buy by clicking a series of buttons on panel.html, the data from those three choices pickOne, pickTwo and pickThree are saved in a query string and is passed to gifts.html
On document.ready or window.onload, the values from the query
string are concatenated and passed to an isotope.js filter, which sorts
the gifts on the page based on the query
Problem
When clicking the next button on the final and third panel, the value of the third pick is not being added to the query string and it is appearing empty pickThree=""
If I paste the url to go directly to that URL with the querystring,
the page doesn't appear to filter results on document.ready or
window.onload
scripts.js
// Pass choices to query string
var pickOne = null;
var pickTwo = null;
var pickThree = null;
$(".btn--next").on("click", function(){
// Progress bar circles
var circleOneSelected = $(".circle--one").hasClass("is-selected");
var circleTwoSelected = $(".circle--two").hasClass("is-selected");
var circleThreeSelected = $(".circle--three").hasClass("is-selected");
// Panel One options
var giftsforHimSelected = $(".btn--option-him").hasClass("is-selected");
var giftsforHerSelected = $(".btn--option-her").hasClass("is-selected");
var giftsforKidsSelected = $(".btn--option-kids").hasClass("is-selected");
var giftsforAnyoneSelected = $(".btn--option-anyone").hasClass("is-selected");
// Panel Two options
var typeHimJewelry = $(".btn--option-him-jewelry").hasClass("is-selected");
var typeHimScarves = $(".btn--option-him-scarves").hasClass("is-selected");
var typeHimFishing = $(".btn--option-him-fishing").hasClass("is-selected");
var typeHimCologne = $(".btn--option-him-cologne").hasClass("is-selected");
var typeHimShirts = $(".btn--option-him-shirts").hasClass("is-selected");
var typeHimSports = $(".btn--option-him-sports").hasClass("is-selected");
var typeHerCashmere = $(".btn--option-her-cashmere").hasClass("is-selected");
var typeHerPerfume = $(".btn--option-her-perfume").hasClass("is-selected");
var typeHerScarves = $(".btn--option-her-scarves").hasClass("is-selected");
var typeHerSweaters = $(".btn--option-her-sweaters").hasClass("is-selected");
var typeHerBeauty = $(".btn--option-her-beauty").hasClass("is-selected");
var typeHerCandles = $(".btn--option-her-candles").hasClass("is-selected");
var typeHerNecklaces = $(".btn--option-her-necklaces").hasClass("is-selected");
var typeHerJewelry = $(".btn--option-her-jewelry").hasClass("is-selected");
var typeHerWatches = $(".btn--option-her-watches").hasClass("is-selected");
var typeHerBags = $(".btn--option-her-bags").hasClass("is-selected");
var typeHerShoes = $(".btn--option-her-shoes").hasClass("is-selected");
var typeHerOther = $(".btn--option-her-other").hasClass("is-selected");
var typeAnyoneCookbooks = $(".btn--option-anyone-cookbooks").hasClass("is-selected");
var typeAnyoneSpirits = $(".btn--option-anyone-spirits").hasClass("is-selected");
var typeAnyoneSuitcases = $(".btn--option-anyone-suitcases").hasClass("is-selected");
var typeAnyoneFood = $(".btn--option-anyone-food").hasClass("is-selected");
var typeAnyoneGardening = $(".btn--option-anyone-gardening").hasClass("is-selected");
var typeAnyoneGadgets = $(".btn--option-anyone-gadgets").hasClass("is-selected");
var typeAnyoneStLouis = $(".btn--option-anyone-stlouis").hasClass("is-selected");
var typeAnyoneGiveBack = $(".btn--option-anyone-giveback").hasClass("is-selected");
var typeAnyoneFitness = $(".btn--option-anyone-fitness").hasClass("is-selected");
var typeAnyoneSubscriptions = $(".btn--option-anyone-subscriptions").hasClass("is-selected");
var typeAnyoneOrnaments = $(".btn--option-anyone-ornaments").hasClass("is-selected");
var typeAnyonePets = $(".btn--option-anyone-pets").hasClass("is-selected");
var typeAnyonePersonalized = $(".btn--option-anyone-other").hasClass("is-selected");
var typeAnyoneOther = $(".btn--option-anyone-other").hasClass("is-selected");
// Panel Three options
var under25 = $(".btn--option-25").hasClass("is-selected");
var under50 = $(".btn--option-50").hasClass("is-selected");
var under75 = $(".btn--option-75").hasClass("is-selected");
var under100 = $(".btn--option-100").hasClass("is-selected");
var under250 = $(".btn--option-u250").hasClass("is-selected");
var over250 = $(".btn--option-o250").hasClass("is-selected");
var btnLikeSelected = $(".btn--like").hasClass("is-selected");
var btnSpendSelected = $(".btn--spend").hasClass("is-selected");
// // Pass choices to query string
// var pickOne = "";
// var pickTwo = "";
// var pickThree = "";
var data = {
pickOne: pickOne,
pickTwo: pickTwo,
pickThree: pickThree
}
if (circleOneSelected) {
if (giftsforHimSelected) {
completeStepOne();
showPanelHim();
pickOne = ".GiftsForHim";
console.log(pickOne);
} else if (giftsforHerSelected) {
completeStepOne();
showPanelHer();
pickOne = ".GiftsForHer";
console.log(pickOne);
} else if (giftsforKidsSelected) {
completeStepsOneTwo();
showPanelThree();
pickOne = ".GiftsForKids";
console.log(pickOne);
} else if (giftsforAnyoneSelected) {
completeStepOne();
showPanelAnyone();
pickOne = ".GiftsForAnyone";
console.log(pickOne);
}
}
if (circleTwoSelected && btnLikeSelected) {
completeStepTwo();
showPanelThree();
// Gifts he might like
if (typeHimJewelry) {
pickTwo = ".Jewelry";
} else if (typeHimScarves) {
pickTwo = ".Scarves";
} else if (typeHimFishing) {
pickTwo = ".Fishing";
} else if (typeHimCologne) {
pickTwo = ".Cologne";
} else if (typeHimShirts) {
pickTwo = ".Shirts";
} else if (typeHimSports) {
pickTwo = ".Sports";
// Gifts she might like
} else if (typeHerCashmere) {
pickTwo = ".Cashmere";
} else if (typeHerPerfume) {
pickTwo = ".Perfume";
} else if (typeHerScarves) {
pickTwo = ".Scarves";
} else if (typeHerSweaters) {
pickTwo = ".Sweaters";
} else if (typeHerBeauty) {
pickTwo = ".Beauty";
} else if (typeHerCandles) {
pickTwo = ".Candles";
} else if (typeHerNecklaces) {
pickTwo = ".Necklaces";
} else if (typeHerJewelry) {
pickTwo = ".SportsJewelry";
} else if (typeHerWatches) {
pickTwo = ".Watches";
} else if (typeHerBags) {
pickTwo = ".SuitcasesBags";
} else if (typeHerShoes) {
pickTwo = ".Shoes";
} else if (typeHerOther) {
pickTwo = ".Other";
// Gifts they might like
} else if (typeAnyoneCookbooks) {
pickTwo = ".Cookbooks";
} else if (typeAnyoneSpirits) {
pickTwo = ".Spirits";
} else if (typeAnyoneSuitcases) {
pickTwo = ".Suitcases";
} else if (typeAnyoneFood) {
pickTwo = ".Food";
} else if (typeAnyoneGardening) {
pickTwo = ".Garden";
} else if (typeAnyoneGadgets) {
pickTwo = ".Gadgets";
} else if (typeAnyoneStLouis) {
pickTwo = ".StLouis";
} else if (typeAnyoneGiveBack) {
pickTwo = ".GiveBack";
} else if (typeAnyoneFitness) {
pickTwo = ".Fitness";
} else if (typeAnyoneSubscriptions) {
pickTwo = ".Subscription";
} else if (typeAnyoneOrnaments) {
pickTwo = ".Ornaments";
} else if (typeAnyonePets) {
pickTwo = ".Pets";
} else if (typeAnyonePersonalized) {
pickTwo = ".Personalized";
} else if (typeAnyoneOther) {
pickTwo = ".Other";
}
}
if (circleThreeSelected && btnSpendSelected) {
if (under25) {
var pickThree = ".Under25";
} else if (under50) {
var pickThree = ".Under50";
} else if (under75) {
var pickThree = ".Under75";
} else if (under100) {
var pickThree = ".Under100";
} else if (under250) {
var pickThree = ".Under250";
} else if (over250) {
var pickThree = ".Over250";
}
var query = jQuery.param(data);
window.open("http://staging.graphics.stltoday.com/apps/giftguide/gifts.html?"+query);
}
});
gifts.html
This script should run if the final next button is clicked on panel.html or going directly to that URL
<script>
$(function(){
// if (window.location.href.indexOf("?" && "pickOne=." && "pickTwo=." && "pickThree=.") !== -1) {
if (window.location.href.indexOf("?") !== -1) {
console.log(window.location.href);
function getParameterByName(name, url) {
if (!url) {
url = window.location.href;
}
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var paramOne = getParameterByName("pickOne");
var paramTwo = getParameterByName("pickTwo");
var paramThree = getParameterByName("pickThree");
var filter = paramOne+paramTwo+paramThree
console.log(filter);
var $grid = $('.gifts').isotope({
itemSelector: '.gift',
layoutMode: 'masonry',
getSortData: {
name: '.gift__name',
price: '.gift__price parseInt',
},
sortAscending: {
name: true,
price: true
}
});
$grid.isotope({ filter: filter });
// If your query returns zero results, then make another search
var filter = $('.gifts').filter(function () {
return this.style.display == 'none'
});
if (filter.length === 0) {
console.log("There are no results");
}
}
});
</script>
panel.html
<!-- Panel Three -->
<div class="panel panel--three is-hidden">
<!-- <div class="advertising advertising--horizontal">
<img src="http://placehold.it/720x90">
</div> -->
<div class="panel__inner inner--spend">
<div class="panel__info">
<h2 class="panel__title">How much do you want to spend?</h2>
<h3 class="panel__instructions pick--one">Pick one of the options below</h3>
<!-- <h3 class="panel__instructions">Remember, it's the thought that counts</h3> -->
</div>
<div class="button__group">
<button class="btn btn--option btn--option-25 btn--spend">Under $25 <i class="fa fa-check is-grey" aria-hidden="true"></i></button>
<button class="btn btn--option btn--option-50 btn--spend">Under $50 <i class="fa fa-check is-grey" aria-hidden="true"></i></button>
<button class="btn btn--option btn--option-75 btn--spend">Under $75 <i class="fa fa-check is-grey" aria-hidden="true"></i></button>
<button class="btn btn--option btn--option-100 btn--spend">Under $100 <i class="fa fa-check is-grey" aria-hidden="true"></i></button>
<button class="btn btn--option btn--option-u250 btn--spend">Under $250 <i class="fa fa-check is-grey" aria-hidden="true"></i></button>
<button class="btn btn--option btn--option-o250 btn--spend">$250 and over <i class="fa fa-check is-grey" aria-hidden="true"></i></button>
</div>
<div class="button__group button__controls">
<button class="btn btn--previous previous--three"><i class="fa fa-long-arrow-left" aria-hidden="true"></i> Previous</button>
<button class="btn btn--next next--three">Next <i class="fa fa-long-arrow-right" aria-hidden="true"></i></button>
</div>
</div> <!-- .panel__inner -->
</div> <!-- .panel .panel--three -->

You are creating new pickThree instances using the var keyword, so the original pickThree instance that was added to data never gets set with a value. You need to remove the var keywords like so:
if (under25) {
pickThree = ".Under25";
} else if (under50) {
pickThree = ".Under50";
} else if (under75) {
pickThree = ".Under75";
} else if (under100) {
pickThree = ".Under100";
} else if (under250) {
pickThree = ".Under250";
} else if (over250) {
pickThree = ".Over250";
}

Related

Calculator doesn't display result [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 months ago.
Improve this question
*This calculator is only for one digit calculations
In my code there are 3 textboxes Two for values and one for Operators.
I want that if first textbox isn't empty and user clicks on any number than that value should be added in another textbox.
When I click Enter it doesn't display result and I didn't show any kind of error in console
// Textboxes, Enter and Reset
var txt1 = document.querySelector("#txt1");
var txt2 = document.querySelector("#txt2");
var txt3 = document.querySelector("#txt3");
var ent = document.querySelector("#ent");
var res = document.querySelector("#res");
// Number-Buttons
var b1 = document.querySelector("#b1");
var b2 = document.querySelector("#b2");
var b3 = document.querySelector("#b3");
var b4 = document.querySelector("#b4");
var b5 = document.querySelector("#b");
var b6 = document.querySelector("#b6");
var b7 = document.querySelector("#b7");
var b8 = document.querySelector("#b8");
var b9 = document.querySelector("#b9");
// Operators
var add = document.querySelector("#add");
var sub = document.querySelector("#sub");
var mul = document.querySelector("#mul");
var div = document.querySelector("#div");
if (txt1.value == "") {
function B1() { txt1.value = "1" }
function B2() { txt1.value = "2" }
function B3() { txt1.value = "3" }
function B4() { txt1.value = "4" }
function B5() { txt1.value = "5" }
function B6() { txt1.value = "6" }
function B7() { txt1.value = "7" }
function B8() { txt1.value = "8" }
function B9() { txt1.value = "9" }
if (txt2.value == "") {
function Add() { txt2.value = "+" }
function Sub() { txt2.value = "-" }
function Mul() { txt2.value = "*" }
function Div() { txt2.value = "/" }
}
// if (txt1.value != "" && txt3.value == "") {
// function B1() { txt3.value = "1" }
// function B2() { txt3.value = "2" }
// function B3() { txt3.value = "3" }
// function B4() { txt3.value = "4" }
// function B5() { txt3.value = "5" }
// function B6() { txt3.value = "6" }
// function B7() { txt3.value = "7" }
// function B8() { txt3.value = "8" }
// function B9() { txt3.value = "9" }
// }
}
function Ent() {
if (txt1.value == "" || txt2.value == "" || txt3.value == "") {
alert("Pls Enter values and select the operator");
}
function sum() {
if (txt2.value == "+") {
var Sum = Number(txt1.value) + Number(txt3.value);
alert(Sum);
console.log(Sum);
}
}
function sub() {
if (txt2.value == "-") {
var Sub = Number(txt1.value) - Number(txt3.value);
alert(Sub);
console.log(Sub);
}
}
function mul() {
if (txt2.value == "*") {
var Mul = Number(txt1.value) * Number(txt3.value);
alert(Mul);
console.log(Mul);
}
}
function div() {
if (txt2.value == "/") {
var Div = Number(txt1.value) / Number(txt3.value);
alert(Div);
console.log(Div);
}
}
}
I tried to understand what you want to do from the code you shared. In the solution you developed, I made subtractions as the numbers are defined as separate buttons. In this direction, I developed a lean solution. This program is used as follows:
Use the numeric keypad to enter the first number.
Click the action you want to perform (+, -, *, /)
Use the numeric keypad to enter the second number.
Click the CALCULATE button to see the result.
Click the CLEAR button to clear the screen.
var firstNumberText = document.getElementById("txt1");
var secondNumberText = document.getElementById("txt2");
var operatorText = document.getElementById("txt3");
var operationText = document.getElementById("txt4");
var resultText = document.getElementById("txt5");
var addButton = document.getElementById("add");
var subButton = document.getElementById("sub");
var mulButton = document.getElementById("mul");
var divButton = document.getElementById("div");
var enterButton = document.getElementById("enter");
var clearButton = document.getElementById("clear");
let status = true;
let currentFirstNumber = "";
let currentSecondNumber = "";
function updateText(){
firstNumberText.innerText = currentFirstNumber;
secondNumberText.innerText = currentSecondNumber;
}
function changeState(operator) {
operatorText.innerText = operator;
status = !status;
}
addButton.addEventListener("click", function() {
changeState("+");
});
subButton.addEventListener("click", function() {
changeState("-");
});
mulButton.addEventListener("click", function() {
changeState("*");
});
divButton.addEventListener("click", function() {
changeState("/");
});
function numberPressed(pressedButton) {
if(status)
currentFirstNumber += pressedButton.value;
else
currentSecondNumber += pressedButton.value;
}
function updateResult(result, operator) {
operationText.innerText = firstNumberText.textContent + operator + secondNumberText.textContent + "=" + `${result}`;
resultText.innerText = result;
}
function calculate() {
if (firstNumberText.value == "" || secondNumberText.value == "" || operatorText.value == "") {
alert("Warning");
return;
}
var result = 0;
if(operatorText.textContent == "+") {
result = parseInt(firstNumberText.textContent) + parseInt(secondNumberText.textContent);
updateResult(result, "+");
}
else if(operatorText.textContent == "-") {
result = parseInt(firstNumberText.textContent) - parseInt(secondNumberText.textContent);
updateResult(result, "-");
}
else if(operatorText.textContent == "*") {
result = parseInt(firstNumberText.textContent) * parseInt(secondNumberText.textContent);
updateResult(result, "*");
}
else if(operatorText.textContent == "/") {
result = parseInt(firstNumberText.textContent) / parseInt(secondNumberText.textContent);
updateResult(result, "/");
}
}
enterButton.addEventListener("click", function() {
calculate();
});
clearButton.addEventListener("click", function() {
status = true;
currentFirstNumber = "";
currentSecondNumber = "";
firstNumberText.innerText = "";
secondNumberText.innerText = "";
operatorText.innerText = "";
operationText.innerText = "";
resultText.innerText = "";
});
<!-- First Number -->
<label id="txt1">-</label><br>
<!-- Operator -->
<label id="txt3">-</label><br>
<!-- Second Number -->
<label id="txt2">-</label><br>
<!-- Operation -->
<label id="txt4">-</label><br>
<!-- Result -->
<label id="txt5">-</label><br>
<button type="button" value="0" onclick='numberPressed(this);updateText()'>0</button>
<button type="button" value="1" onclick='numberPressed(this);updateText()'>1</button>
<button type="button" value="2" onclick='numberPressed(this);updateText()'>2</button>
<button type="button" value="3" onclick='numberPressed(this);updateText()'>3</button>
<button type="button" value="4" onclick='numberPressed(this);updateText()'>4</button>
<button type="button" value="5" onclick='numberPressed(this);updateText()'>5</button>
<button type="button" value="6" onclick='numberPressed(this);updateText()'>6</button>
<button type="button" value="7" onclick='numberPressed(this);updateText()'>7</button>
<button type="button" value="8" onclick='numberPressed(this);updateText()'>8</button>
<button type="button" value="9" onclick='numberPressed(this);updateText()'>9</button>
<br><br>
<button type="button" id="add">+</button>
<button type="button" id="sub">-</button>
<button type="button" id="mul">*</button>
<button type="button" id="div">/</button><br><br>
<button type="button" id="enter">CALCULATE</button>
<button type="button" id="clear">CLEAR</button>

comment appending on the first post only in Vanilla JavaScript

I am creating a status posting and commenting system.
It is implemented in Vanilla JavaScript. Anyone can add a post and can comment on the post.
Everything is working fine but the comment section is working on first post only.
deletion of comment and post is working fine.
I don't know what's the problem is, if anyone could help me..
Here is the HTML code
<div class="container-post" id="container-post">
<div class="create-post">
<form>
<div class="form-group">
<div class="username">
<p class="name" style="top:15px;">User Name</p>
</div>
<p class="qoutes">
<textarea style=" font-size: 15pt;" class="form-control" id="enter-post" rows="7" id="mypara" placeholder="Share Your Thoughts..."></textarea>
</p>
<div class="postbar">
<button type="button" class="btn btn-primary post-me" id="post-button"> <span id="postText">Post</span></button>
</div>
</div>
</form>
</div>
<hr class="line-bar">
<div class="allpost">
<div class="mainpost" id="post-div"></div>
</div>
Here is the JavaSCript code
showTask();
showComment();
let addPost = document.getElementById("enter-post");
let addPostBtton = document.getElementById("post-button");
addPostBtton.addEventListener("click", function () {
var addPostVal = addPost.value;
if (addPostVal.trim() != 0) {
let webtask = localStorage.getItem("localtask");
if (webtask == null) {
var taskObj = [];
}
else {
taskObj = JSON.parse(webtask);
}
taskObj.push(addPostVal);
localStorage.setItem("localtask", JSON.stringify(taskObj));
}
showTask();
});
function showTask() {
let webtask = localStorage.getItem("localtask");
if (webtask == null) {
var taskObj = [];
}
else {
taskObj = JSON.parse(webtask);
}
let htmlVal = '';
let createPost = document.getElementById("post-div");
taskObj.forEach((item, index) => {
htmlVal += `
<div class="post-class"><div class="username u-name">
<p class="name i-name">${"User Name " + index}</p>
<i class="fas fa-trash-alt" onclick="removePost(${index});"></i></button>
</div>
<hr>
<p class="quotes">
${item}
</p>
<div class="comment-section" id="comment-section">
<p class="comment-qoute">
<textarea style=" font-size: 15pt;" class="form-control commentBox" rows="3" id="mypara" placeholder="Leave a comment"></textarea>
</p>
<button class="btn btn-primary comment-btn" id="commentBtn">comment</button>
<ul class="comments" id="comments-portion">
<p></p>
</ul>
</div>
</div>
<br><br>`
});
createPost.innerHTML = htmlVal;
}
function removePost(index) {
let webtask = localStorage.getItem("localtask");
let taskObj = JSON.parse(webtask);
taskObj.splice(index, 1);
localStorage.setItem("localtask", JSON.stringify(taskObj));
showTask();
}
var commentPost = document.getElementById('mypara');
var commentBtn = document.getElementById('commentBtn');
commentBtn.addEventListener('click', function () {
var commentValue = commentPost.value;
if (commentValue.trim() != 0) {
let commentTask = localStorage.getItem("comments");
if (commentTask == null) {
var commentObj = [];
}
else {
commentObj = JSON.parse(commentTask);
}
commentObj.push(commentValue);
localStorage.setItem("comments", JSON.stringify(commentObj));
}
showComment();
});
function showComment() {
let commentsTask = localStorage.getItem("comments");
if (commentsTask == null) {
var commentObj = [];
}
else {
commentObj = JSON.parse(commentsTask);
}
let commentHTMLValue = '';
var createComment = document.getElementById("comments-portion");
commentObj.forEach((item, index) => {
commentHTMLValue += `<div class="comment-box-btn">
<p>${index + ". "}<span>${item}</span></p>
<i class="far fa-times-circle fa-2x" onclick="removeComment(${index});"></i>
</div>
`;
});
createComment.innerHTML = commentHTMLValue;
}
var deleteBtn = document.querySelector('.comment-del');
deleteBtn.addEventListener('click', () => {
});
// remove comment
function removeComment(index) {
let commentTask = localStorage.getItem("comments");
let commentObj = JSON.parse(commentTask);
commentObj.splice(index, 1);
localStorage.setItem("comments", JSON.stringify(commentObj));
showComment();
}
When you use code like:
createComment.innerHTML = commentHTMLValue;
you are completely replacing the contents of the element. Try using:
createComment.innerHTML += commentHTMLValue;
which appends new content to the end of the existing contents.
I can't do a snippet here as the use of localStorage is not allowed. Copy this block into a blank file and save it as an html file and then open that in a browser.
This is how I think you are describing your requirements and is also based on the data format in my comments. It's not pretty and needs plenty of sprucing up, but it runs.
<!DOCTYPE html>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
<html>
<head>
<title>Task listing</title>
<script type="text/javascript">
let taskList = [];
function checkTasks() {
let tasksList = getTasksList();
if (tasksList.length == 0) {
let newTask = prompt("Please enter a task description");
if (newTask) {
let thisIndex = getNewIndex();
let a = {"id": thisIndex, "task": newTask, "comments": []}
taskList.push(a);
saveTasksList(taskList);
}
}
displayTasks();
}
function displayTasks() {
let container = document.getElementById("tasks");
container.innerHTML = "";
let taskList = getTasksList();
taskList.forEach(function(task){
let d = document.createElement("div");
d.id = "task_" + task.id;
d.className = "commentdiv";
d.innerHTML = "<h3>" + task.task + "</h3>";
let l = document.createElement("ul");
l.id = "comments_" + task.id;
let comments = task.comments;
if (comments.length > 0) {
let commentindex = 0;
comments.forEach(function(comment) {
let c = document.createElement("li");
c.innerHTML = comment;
let cb = document.createElement("button");
cb.id = "deletecomment_" + task.id + "_" + commentindex;
cb.innerHTML = "Delete comment";
cb.onclick = function() {deleteComment(task.id, commentindex);};
c.appendChild(cb);
l.appendChild(c);
})
}
let b = document.createElement("button");
b.id = "addcomment_" + task.id;
b.onclick = function() {addComment(task.id);};
b.innerHTML = "Add comment";
d.appendChild(b);
d.appendChild(l);
container.appendChild(d);
})
}
function addComment(taskid) {
let newcomment = prompt("Enter comment");
if (newcomment) {
let tasklist = getTasksList();
let filtered = tasklist.filter(task => task.id == taskid);
if (filtered[0]) {
let thisTask = filtered[0];
thisTask.comments.push(newcomment);
let thisIndex = taskList.findIndex((task) => task.id == taskid);
taskList[thisIndex] = thisTask;
}
saveTasksList(taskList);
displayTasks();
}
}
function addNewTask() {
let newTask = prompt("Enter task description");
let taskList = getTasksList();
let lastindex = localStorage.getItem("tasksindex");
let index = getNewIndex();
let a = {"id": index, "task": newTask, "comments": []}
taskList.push(a);
saveTasksList(taskList);
displayTasks();
}
function deleteComment(taskid, commentindex) {
let tasklist = getTasksList();
let filtered = tasklist.filter(task => task.id == taskid);
// as long as there is at least one task with the taskid value, find and delete the comment
// based on the index position of the comment in the comments array
if (filtered[0]) {
let thisTask = filtered[0];
thisTask.comments.splice(commentindex, 1);
let thisIndex = taskList.findIndex((task) => task.id == taskid);
taskList[thisIndex] = thisTask;
}
saveTasksList(taskList);
displayTasks();
}
function getTasksList() {
let tasks = localStorage.getItem("tasks");
taskList = JSON.parse(tasks);
if (!taskList) {
taskList = [];
}
return taskList;
}
function saveTasksList(taskList) {
localStorage.setItem("tasks", JSON.stringify(taskList));
}
function getNewIndex() {
let lastindex = localStorage.getItem("tasksindex");
let idx = 0;
if (!lastindex) {
idx = 1;
} else {
idx = Number(lastindex) + 1;
}
localStorage.setItem("tasksindex", idx);
return idx;
}
function removeAll() {
localStorage.removeItem("tasks");
localStorage.removeItem("tasksindex");
displayTasks();
}
window.onload = checkTasks;
</script>
<style type="text/css">
.commentdiv {
border:1px solid black;
width:1000px;
padding:5px;
border-radius:5px;
}
button {
margin-left:10px;
}
h3 {
width:100%;
border-bottom: 1px dotted black;
}
ul {
list-style-type:decimal;
}
</style>
</head>
<body>
<h2>My task list <button id="addNewTaskButton" onclick="addNewTask();">Add new task</button></h2>
<hr>
<div id="tasks">
</div>
<button id="removeAll" onclick="removeAll();">Remove all tasks</button>
</body>
</html>

Uncheck checkbox if another is selected

So i have the following 2 checkboxes on my page on small script attached to it which is designed to hide the billing section.
<script>
function myFunction2() {
var x = document.getElementById("billing_info");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
I'm using the below script to try and uncheck the checkboxes
<script>
$(document).ready( function a()
{
if ( $('#sameAsBilling').is(':checked'))
{
$('#check2').attr('checked', false);
}
});
</script>
<div class="header">
<h3 class="checkout-headers">STEP 3 - Billing Information </h3>
<!--START: sameAsBilling1-->
<!--value="ON"-->
<div class="sameAsBilling1">
<input type="checkbox" name="sameAsBilling" id="sameAsBilling" onclick="showHideShipping();check_address('');"/>
<label for="sameAsBilling">Same as Delivery Address</label>
<div class="clear"></div>
</div>
<div class="differentBilling">
<input type="checkbox" class="example" id="check2" onclick="myFunction2()"; return false;>Different Billing Address?</div>
<!--END: sameAsBilling1-->
<div class="clear"></div>
</div>
My problem is someone as buried the following code in a javascript file which is what transfers the delivery details onto the billing details if the specific checkbox is ticked.
function showHideShipping() {
if (document.billing.sameAsBilling.checked) {
add_overlay("billing_info", 0);
if (get_Element('billing_firstname').value != get_Element('shipping_firstname').value) {
get_Element('billing_firstname').value = get_Element('shipping_firstname').value;
get_Element('billing_lastname').value = get_Element('shipping_lastname').value;
get_Element('billing_company').value = get_Element('shipping_company').value;
get_Element('billing_phone').value = get_Element('shipping_phone').value;
get_Element('billing_address').value = get_Element('shipping_address').value;
get_Element('billing_address2').value = get_Element('shipping_address2').value;
get_Element('billing_city').value = get_Element('shipping_city').value;
get_Element('billing_zip').value = get_Element('shipping_zip').value;
get_Element('billing_country').value = get_Element('shipping_country').value;
populateState('billing_state', 'billing_country');
get_Element('billing_state').value = get_Element('shipping_state').value;
}
} else {
remove_overlay("billing_info");
get_Element('billing_firstname').value = '';
get_Element('billing_lastname').value = '';
get_Element('billing_company').value = '';
get_Element('billing_phone').value = '';
get_Element('billing_address').value = '';
get_Element('billing_address2').value = '';
get_Element('billing_city').value = '';
get_Element('billing_zip').value = '';
get_Element('billing_country').value = get_Element('shipping_country').value;
populateState('billing_state', 'billing_country');
get_Element('billing_state').value = get_Element('shipping_state').value;
}
}
You're missing an else. So the code that hides the billing info and copies the shipping info to it is executed all the time, regardless of the state of the checkbox.
if (document.billing.sameAsBilling.checked) {
add_overlay("billing_info", 0);
get_Element('billing_firstname').value = '';
get_Element('billing_lastname').value = '';
get_Element('billing_company').value = '';
get_Element('billing_phone').value = '';
get_Element('billing_address').value = '';
get_Element('billing_address2').value = '';
get_Element('billing_city').value = '';
get_Element('billing_zip').value = '';
get_Element('billing_country').value = get_Element('shipping_country').value;
populateState('billing_state', 'billing_country');
get_Element('billing_state').value = get_Element('shipping_state').value;
} else {
remove_overlay("billing_info");
if (get_Element('billing_firstname').value != get_Element('shipping_firstname').value) {
get_Element('billing_firstname').value = get_Element('shipping_firstname').value;
get_Element('billing_lastname').value = get_Element('shipping_lastname').value;
get_Element('billing_company').value = get_Element('shipping_company').value;
get_Element('billing_phone').value = get_Element('shipping_phone').value;
get_Element('billing_address').value = get_Element('shipping_address').value;
get_Element('billing_address2').value = get_Element('shipping_address2').value;
get_Element('billing_city').value = get_Element('shipping_city').value;
get_Element('billing_zip').value = get_Element('shipping_zip').value;
get_Element('billing_country').value = get_Element('shipping_country').value;
populateState('billing_state', 'billing_country');
get_Element('billing_state').value = get_Element('shipping_state').value;
}
}

2 button in the same form with speech api

I need use two button in the same page to control two diferent textarea with speech api
When I click on the button to enable the microphone that you type in a textarea, and when click the other button to enable the microphone type in another text area all within the same form by calling the speech API i was watching to use the getElementsByTagName or the getElementsByClassName but i don't has so far proven nothing good
showInfo('info_start');
var final_transcript = '';
var recognizing = false;
var ignore_onend;
var start_timestamp;
if (!('webkitSpeechRecognition' in window)) {
upgrade();
} else {
start_button.style.display = 'inline-block';
var recognition = new webkitSpeechRecognition();
recognition.continuous = true;
recognition.interimResults = false;
recognition.lang = "es-BO";
recognition.onstart = function() {
recognizing = true;
showInfo('info_speak_now');
start_img.src = 'mic-animate.gif';
};
recognition.onerror = function(event) {
if (event.error == 'no-speech') {
start_img.src = 'mic.gif';
showInfo('info_no_speech');
ignore_onend = true;
}
if (event.error == 'audio-capture') {
start_img.src = 'mic.gif';
showInfo('info_no_microphone');
ignore_onend = true;
}
if (event.error == 'not-allowed') {
if (event.timeStamp - start_timestamp < 100) {
showInfo('info_blocked');
} else {
showInfo('info_denied');
}
ignore_onend = true;
}
};
recognition.onend = function() {
recognizing = false;
if (ignore_onend) {
return;
}
start_img.src = 'mic.gif';
if (!final_transcript) {
showInfo('info_start');
return;
}
showInfo('');
if (window.getSelection) {
window.getSelection().removeAllRanges();
var range = document.createRange();
range.selectNode(document.getElementById('final_span'));
window.getSelection().addRange(range);
}
};
recognition.onresult = function(event) {
var interim_transcript = '';
for (var i = event.resultIndex; i < event.results.length; ++i) {
if (event.results[i].isFinal) {
final_transcript += event.results[i][0].transcript;
} else {
interim_transcript += event.results[i][0].transcript;
}
}
final_transcript = final_transcript;
final_span.innerHTML = linebreak(final_transcript);
interim_span.innerHTML = linebreak(interim_transcript);
if (final_transcript || interim_transcript) {
showButtons('inline-block');
}
};
}
function upgrade() {
start_button.style.visibility = 'hidden';
showInfo('info_upgrade');
}
var two_line = /\n\n/g;
var one_line = /\n/g;
function linebreak(s) {
return s.replace(two_line, '<p></p>').replace(one_line, '<br>');
}
var first_char = /\S/;
function startButton2(event) {
if (recognizing) {
recognition.stop();
return;
}
final_transcript = '';
recognition.lang ="es-BO";
recognition.start();
ignore_onend = false;
final_span.innerHTML = '';
interim_span.innerHTML = '';
start_img.src = 'mic-slash.gif';
showInfo('info_allow');
showButtons('none');
start_timestamp = event.timeStamp;
}
function showInfo(s) {
if (s) {
for (var child = info.firstChild; child; child = child.nextSibling) {
if (child.style) {
child.style.display = child.id == s ? 'inline' : 'none';
}
}
info.style.visibility = 'visible';
} else {
info.style.visibility = 'hidden';
}
}
var current_style;
function showButtons(style) {
if (style == current_style) {
return;
}
current_style = style;
}
<div >
<p>
<button id="start_button" onclick="startButton(event)">
<img id="start_img" src="mic.gif" alt="Start"></button>
<textarea id="final_span" class="final"></textarea>
<span id="interim_span" class="interim"></span>
</p>
</div>
<a>---------------------------------------------------</a>
<div >
<p>
<button id="start_button" onclick="startButton(event)">
<img id="start_img" src="mic.gif" alt="Start"></button>
<textarea id="final_span" class="final"></textarea>
<span id="interim_span" class="interim"></span>
</p>
</div>
You need to change the onclick of the second button to startButton2(event) to call your second function.
<div >
<p>
<button id="start_button" onclick="startButton(event)">
<img id="start_img" src="mic.gif" alt="Start"></button>
<textarea id="final_span" class="final"></textarea>
<span id="interim_span" class="interim"></span>
</p>
</div>
<a>---------------------------------------------------</a>
<div >
<p>
<button id="start_button" onclick="startButton2(event)">
<img id="start_img" src="mic.gif" alt="Start"></button>
<textarea id="final_span" class="final"></textarea>
<span id="interim_span" class="interim"></span>
</p>
</div>

Add or Clear localStorage on button click and show the value in html

I have a code that uses localStorage and javascript. I tried to add more slots, like slot1, slot2, slot3 up to 5. I just copy and paste then change the variable names like like slot1, slot2, slot3 up to 5. But it won't work. Help will be appreciated so much.
Javascript:
var slot = localStorage.getItem("slot");
if (slot == null) {
slot = 10;
}
document.getElementById("slot").innerText = slot;
function reduceSlot() {
if (slot >= 1) {
slot--;
localStorage.setItem("slot", slot);
if (slot > 0) {
document.getElementById('slot').innerText = slot;
} else {
document.getElementById('slot').innerText = "FULL";
document.getElementById("button1").style.display = "none";
}
}
}
document.getElementById("button1").onclick = reduceSlot;
function clearLocalStorage() {
localStorage.clear();
}
HTML:
<p id="slot">10</p>
Deduct
<button onclick="window.localStorage.clear();">Clear All</button>
Fiddle: http://jsfiddle.net/barmar/K8stQ/3/
not sure but. is this what you want to do?? working demo
i changed your code a bit.. you can change it into your liking later..
<span id="slot0">10</span><input type="button" value="Deduct" onclick="(function(){reduceSlot(0)})()" ><br>
<span id="slot1">10</span><input type="button" value="Deduct" onclick="(function(){reduceSlot(1)})()" ><br>
<span id="slot2">10</span><input type="button" value="Deduct" onclick="(function(){reduceSlot(2)})()" ><br>
<span id="slot3">10</span><input type="button" value="Deduct" onclick="(function(){reduceSlot(3)})()" ><br>
<span id="slot4">10</span><input type="button" value="Deduct" onclick="(function(){reduceSlot(4)})()" ><br>
<p>
<button onclick="clearAll()">Clear All</button>
</p>
and for the js...
ls = localStorage.getItem("slots") ;
if(!ls) { localStorage.setItem("slots", "10,10,10,10,10");
}
var slots = localStorage.getItem("slots").split(',').map(Number);
window.onload = updateSlots;
function updateSlots() { for(var i=0;i<slots.length;i++) {
document.getElementById('slot' + i ).innerHTML = slots[i] ;
}}
var reduceSlot = function(slotId) {
console.log(slots[slotId]) ;
if(slots[slotId] >= 1) {
slots[slotId]--; localStorage.setItem("slots",slots);
document.getElementById('slot' + slotId).innerHTML = slots[slotId];
}
else { document.getElementById('slot'+slotId).innerText = "FULL";
}
};
function clearAll() {
window.localStorage.clear();
slots = [10,10,10,10,10];
updateSlots();
}
Try this,
Script
window.ready = function() {
checkStorage();
}
function checkStorage() {
var slot = localStorage.getItem("slot");
if (slot == null) {
slot = 10;
}
document.getElementById("slot").innerHTML = slot;
}
function reduceSlot() {
var slot = localStorage.getItem("slot");
if (slot == null) {
slot = 10;
}
if (slot >= 1) {
slot--;
localStorage.setItem("slot", slot);
if (slot > 0) {
document.getElementById('slot').innerHTML = slot;
} else {
document.getElementById('slot').innerHTML = "FULL";
document.getElementById("button1").style.display = "none";
}
}
}
document.getElementById("button1").onclick = reduceSlot;
document.getElementById("clear").onclick = clear_me;
function clear_me() {
localStorage.clear();
checkStorage();
}
HTML
<p id="slot">10</p>
Deduct
<button id="clear">Clear All</button>
Demo

Categories