javascript not adding/removing divs in set order - javascript

I'm working with JavaScript and am having issues with a couple of for loops at a specific value.
When the slider value is incremented, the amount of pics increase by one and vice versa for when its lowered. However, for a reason I'm unsure of, it will remove one of the pics when the slider is incremented from 9 to 10, and will add one when it's lowered from 10 to 9. This problem doesn't occur anywhere else in the slider, so I'm not sure whats going on.
Here's the code. The picture used isn't attached but the missing image favicon does the same job.
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
var prevnumb = 0;
var num = 2
var numberofdivs = 0;
output.innerHTML = slider.value;
slider.oninput = function() {
prevnum = num;
output.innerHTML = this.value;
num = this.value;
var newnum = num;
var newprevnum = prevnum;
console.log(prevnum, num);
if (prevnum > num) {
for (newnum; newprevnum > newnum; newnum++) {
var element = document.getElementById("id");
element.parentNode.removeChild(element);
}
} else if (num > prevnum) {
for (newprevnum; newnum > newprevnum; newprevnum++) {
var picpol = document.createElement("img");
picpol.src = "polee.png";
picpol.setAttribute("id", "id");
picpol.setAttribute("class", "polio");
document.getElementById("basecontainer").appendChild(picpol);
console.log(picpol);
}
} else {
console.log("no change");
}
}
body {
text-align: center;
}
#basecustom {
text-align: center;
}
.polio {
margin: none;
padding: none;
}
Base Customization
<br>
<br>
<div id="basecustom">
Select your amount of pics
<input type="range" min="2" max="25" value="2" id="myRange">
<p>Value: <span id="demo"></span></p>
<div id="valcont"></div>
<div id="basecontainer">
<img class="polioo" src="polee.png" id="id"><img class="polioo" src="polee.png" id="id">
</div>
</div>

You were missing casting value to int. By default it is string.
num = parseInt(this.value);
Above casting will fix your problem.
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
var prevnumb = 0;
var num = 2
var numberofdivs = 0;
output.innerHTML = slider.value;
slider.oninput = function() {
prevnum = num;
output.innerHTML = this.value;
num = parseInt(this.value);
var newnum = num;
var newprevnum = prevnum;
console.log(prevnum, num);
if (prevnum > num) {
for (newnum; newprevnum > newnum; newnum++) {
var element = document.getElementById("id");
element.parentNode.removeChild(element);
}
} else if (num > prevnum) {
for (newprevnum; newnum > newprevnum; newprevnum++) {
var picpol = document.createElement("img");
picpol.src = "https://www.vyapin.com/blog/wp-content/uploads/2012/07/bullet_04-1.gif";
picpol.setAttribute("id", "id");
picpol.setAttribute("class", "polio");
document.getElementById("basecontainer").appendChild(picpol);
console.log(picpol);
}
} else {
console.log("no change");
}
}
body {
text-align: center;
}
#basecustom {
text-align: center;
}
.polio {
margin: none;
padding: none;
}
Base Customization
<br>
<br>
<div id="basecustom">
Select your amount of pics
<input type="range" min="2" max="25" value="2" id="myRange">
<p>Value: <span id="demo"></span></p>
<div id="valcont"></div>
<div id="basecontainer">
<img class="polioo" src="https://www.vyapin.com/blog/wp-content/uploads/2012/07/bullet_04-1.gif" id="id"/><img class="polioo" src="https://www.vyapin.com/blog/wp-content/uploads/2012/07/bullet_04-1.gif" id="id"/>
</div>
</div>

change num = this.value; to num = parseInt(this.value,10); in your original code, num will be a string. so when it increments to 10, you will get a string '10'. And prevnum is '9'. And if (prevnum > num) { will be true.

Related

How to save multiple user inputs into new variables

Im creating a guessing game and the user has 5 attempts to make the correct guess. I want to save their previous guesses (inputs) to show it to them. I have been using the snippet below to save one attempt when the user types into an <input> field, but how can I save the next 4 attempts in new variables such as userGuess2, userGuess3, etc.
var userGuess = document.getElementById("inputField").value;
$('#previousGuesses').text(userGuess);
Ok then let's pretend this is your input
<input type="text" id="inputField">
You can create an index that will increment everytime the users presses enter to save another answer
var i=1;
And the id name your autogenerated spans will have
var name = "previousGuesses";
Now on your function you will save the value when the user presses enter like you described and when that happens it will create a new span element where it will display the value stored
function myFunction(){
$("#inputField").keypress(function( event ) {
if ( event.which == 13 || event.which == 9) {
var userGuess = document.getElementById("inputField").value;//get value of the answer
var span = document.createElement('SPAN');//create a new span
span.innerHTML = userGuess + "<br>";//answer value goes here
span.id = name+i;//this is the id of your new span, remember ids are unique so we attach var i to the name var we declared before
document.body.appendChild(span);
//$('#previousGuesses'+i).text(userGuess);
i++;
}
});
}
now call your function
myFunction();
https://jsfiddle.net/kenpy/m16bojhg/4/
You can just simply add an element for the user's last attempts and add to it.
f(guessCount === 1) {
guesses.textContent = 'Previous guesses: ';
}
guesses.textContent += userGuess + ' ';
var randomNumber = Math.floor(Math.random() * 100) + 1;
var guesses = document.querySelector('.guesses');
var lastResult = document.querySelector('.lastResult');
var lowOrHi = document.querySelector('.lowOrHi');
var guessSubmit = document.querySelector('.guessSubmit');
var guessField = document.querySelector('.guessField');
var guessCount = 1;
var resetButton;
guessField.focus();
function checkGuess() {
var userGuess = Number(guessField.value);
if(guessCount === 1) {
guesses.textContent = 'Previous guesses: ';
}
guesses.textContent += userGuess + ' ';
if(userGuess === randomNumber) {
lastResult.textContent = "Good job! You win!";
lastResult.style.backgroundColor = 'green';
lowOrHi.textContent = '';
setGameOver();
} else if(guessCount === 10) {
lastResult.textContent = 'Hahaha You suck!';
lowOrHi.textContent = '';
setGameOver();
} else {
lastResult.textContent = "Oops! You're Wrong!";
lastResult.style.backgroundColor = 'red';
if(userGuess < randomNumber) {
lowOrHi.textContent = 'Last guess was too low!';
} else if(userGuess > randomNumber) {
lowOrHi.textContent = 'Last guess was too high!';
}
}
guessCount++;
guessField.value = '';
guessField.focus();
}
guessSubmit.addEventListener('click', checkGuess);
console.log('cheat is: ' + randomNumber);
function setGameOver() {
guessField.disabled = true;
guessSubmit.disabled = true;
resetButton = document.createElement('button');
resetButton.textContent = 'Play Again?';
document.body.appendChild(resetButton);
resetButton.addEventListener('click', resetGame);
}
function resetGame() {
guessCount = 1;
var resetParas = document.querySelectorAll('.resultParas p');
for(var i = 0 ; i < resetParas.length ; i++) {
resetParas[i].textContent = '';
}
resetButton.parentNode.removeChild(resetButton);
guessField.disabled = false;
guessSubmit.disabled = false;
guessField.value = '';
guessField.focus();
lastResult.style.backgroundColor = 'white';
randomNumber = Math.floor(Math.random() * 100) + 1;
}
body{
background-image: linear-gradient(to left top, #c6fced, #a3efda, #7fe3c7, #54d5b3, #00c89f);
color: #2F3139;
margin: 10rem auto;
height:50vh;
}
h1 {
font-size: 1.5rem;
}
.lastResult {
color: white;
padding: 3px;
}
button {
margin-left:3rem ;
}
<h3 class="display-4 text-center text-muted text-capitalize"></h3>
<div class="container">
<div class="row">
<div class="col-md-6 ">
<h1 class="text-muted text-capitalize">
<span class="text-primary">JavaScript</span> Number guessing game</h1>
<p class="lead">Simply enter a number between 1 - 100 then click the button</p>
</div>
<div class="col-md-6">
<div class="mt-4 d-inline-block">
<div class="form">
<label for="guessField">Guess a number : </label><input type="text" id="guessField" class="guessField">
<input type="submit" value="Submit guess" class="guessSubmit">
</div>
<div class="resultParas text-center lead">
<p class="guesses"></p>
<p class="lastResult"></p>
<p class="lowOrHi"></p>
</div>
</div>
</div> </div>
</div>
Resource
JavaScript number guessing game

Cannot set innerHTML on one, of two, identical functions

I have two functions that are essentially identical. The negIndex function works as advertised, no problems, but the posIndex function give me the error "cannot set enterTable.innerHTML to 'null'".
I'm fairly new to Javascript so it could be something obvious, but if it is i'm lost. I've tried a few different things without positive results. Any help would be appreciated.
The HTML
<ul id="exitTable" style="list-style-type: none; display: flex; flex-direction: column; vertical-align: center"></ul>
<br>
<ul id="enterTable" style="list-style-type: none; display: flex; flex-direction: column; vertical-align: center"></ul>
The Javascript
// Put DOM elements into variables
const myForm = document.querySelector('#my-form');
const price = document.querySelector('#stockPrice');
const shares = document.querySelector('#sharesAmount');
const commission = document.querySelector('#commissionAmount');
const fee = document.querySelector('#feeAmount');
const max = document.querySelector('#maxGain');
const msg = document.querySelector('.msg');
const exitTable = document.querySelector('#exitTable');
const enterTable = document.querySelector('#enterTable');
// Listen for form submit
myForm.addEventListener('submit', onSubmit);
function onSubmit(e) {
e.preventDefault();
if (price.value === '' || shares.value === '') {
// alert
msg.classList.add('error');
msg.innerHTML = 'Please enter required fields';
// Remove error after 3 seconds
setTimeout(() => msg.remove(), 3000);
} else {
let subTotal = price.value * shares.value;
subTotal = subTotal.toFixed(2)
let total = subTotal + parseFloat(commission.value);
function popList(name) {
let li = document.createElement('li');
li.textContent = name;
li.style.cssText = 'text-align: center'
return li;
}
//finds the 5%-50% loss amounts based on subTotal
function negIndex(num) {
let negPer = -0.05;
let negArray = [];
let i = 0;
exitTable.innerHTML = "";
while (negPer >= -0.50) {
negArray[i] = parseFloat(num * negPer).toFixed(2);
let s = parseFloat(negPer * 100).toFixed(1) + "% " + negArray[i];
let x = popList(s); //creating list elements
exitTable.appendChild(x);
i++;
negPer += -0.05;
}
}
function posIndex(num) {
let posPer = 0.05;
let posArray = [];
let i = 0;
enterTable.innerHTML = "";
while (posPer <= 1.00) {
posArray[i] = parseFloat(num * posPer).toFixed(2);
let s = parseFloat(posPer * 100).toFixed(1) + "% ->" + posArray[i];
let x = popList(s);
enterTable.appendChild(x);
i++;
posPer += 0.05;
}
}
posIndex(subTotal);
negIndex(subTotal);
}
//Listen for form clear
myForm.addEventListener('reset', onReset);
function onReset() {
price.innerHTML = "";
shares.innerHTML = "";
commission.innerHTML = "";
fee.innerHTML = "";
}
I'm just gessing what your html could look like
// Put DOM elements into variables
const myForm = document.querySelector('#my-form');
const price = document.querySelector('#stockPrice');
const shares = document.querySelector('#sharesAmount');
const commission = document.querySelector('#commissionAmount');
const fee = document.querySelector('#feeAmount');
const max = document.querySelector('#maxGain');
const msg = document.querySelector('.msg');
const exitTable = document.querySelector('#exitTable');
const enterTable = document.querySelector('#enterTable');
let subTotal = 0;
// Listen for form submit
myForm.addEventListener('submit', onSubmit);
function onSubmit(e) {
e.preventDefault();
if (price.value === '' || shares.value === '') {
// alert
msg.classList.add('error');
msg.innerHTML = 'Please enter required fields';
// Remove error after 3 seconds
setTimeout(() => {
msg.classList.remove('error');
msg.innerHTML = '';
}, 3000);
} else {
subTotal = price.value * shares.value;
subTotal = subTotal.toFixed(2)
}
posIndex(subTotal);
negIndex(subTotal);
}
function popList(name) {
let li = document.createElement('li');
li.textContent = name;
li.style.cssText = 'text-align: center'
return li;
}
//finds the 5%-50% loss amounts based on subTotal
function negIndex(num) {
let negPer = -0.05;
let negArray = [];
let i = 0;
exitTable.innerHTML = "";
while (negPer >= -0.50) {
negArray[i] = parseFloat(num * negPer).toFixed(2);
let s = parseFloat(negPer * 100).toFixed(1) + "% " + negArray[i];
let x = popList(s); //creating list elements
exitTable.appendChild(x);
i++;
negPer += -0.05;
}
}
function posIndex(num) {
let posPer = 0.05;
let posArray = [];
let i = 0;
enterTable.innerHTML = "";
while (posPer <= 1.00) {
posArray[i] = parseFloat(num * posPer).toFixed(2);
let s = parseFloat(posPer * 100).toFixed(1) + "% ->" + posArray[i];
let x = popList(s);
enterTable.appendChild(x);
i++;
posPer += 0.05;
}
}
//Listen for form clear
myForm.addEventListener('reset', onReset);
function onReset() {
price.innerHTML = "";
shares.innerHTML = "";
commission.innerHTML = "";
fee.innerHTML = "";
}
<form id="my-form">
<div>
<label for="stockPrice">Stock price</label>
<input type="number" id="stockPrice" />
</div>
<div>
<label for="sharesAmount">Shares amount</label>
<input type="number" id="sharesAmount" />
</div>
<div>
<label for="commissionAmount">Commission amount</label>
<input type="number" id="commissionAmount" />
</div>
<div>
<label for="feeAmount">Fee amount</label>
<input type="number" id="feeAmount" />
</div>
<div>
<label for="maxGain">Max gain</label>
<input type="number" id="maxGain" />
</div>
<div class="msg"></div>
<button type="submit">Submit</button>
</form>
<ul id="exitTable" style="list-style-type: none; display: flex; flex-direction: column; vertical-align: middle"></ul>
<br>
<ul id="enterTable" style="list-style-type: none; display: flex; flex-direction: column; vertical-align: middle"></ul>

Is there a fix for number counter bug using vanilla javascript

I made products quantity counter for e-commerce that should increase and decrease the quantity by 1 and it works only if the elements exist in dom without appending from javascript
but when I click on the get button to append from javascript the last appended element only increases or decreases by one.
here is the code:
class Cart {
static global() {
Cart.getBtn = document.getElementById('get');
Cart.main = document.getElementsByTagName('main')[0];
Cart.min = 1;
}
constructor(num) {
this.num = num;
}
static insertEl() {
const div = document.createElement('div');
div.innerHTML = `
<br>
<div>
<button type="button" class="minus">-</button>
<input type="number" min="1" max="20" value="1">
<button type="button" class="plus">+</button>
</div>
`;
Cart.main.appendChild(div);
}
static plusFunc() {
// plus btn
let plus = document.querySelectorAll('.plus');
plus.forEach(function(btn) {
btn.addEventListener('click', function(e) {
let input = e.target.previousElementSibling;
let max = Number(input.getAttribute('max'));
let num1 = new Cart(Number(input.value));
if (num1.num >= Cart.min) {
num1.num += 1;
}
if (num1.num >= max) {
num1.num = max;
}
input.value = num1.num;
});
});
}
static minusFunc() {
// minus btn
let minus = document.querySelectorAll('.minus');
minus.forEach(function(btn) {
btn.addEventListener('click', function(e) {
let input = e.target.nextElementSibling;
let max = Number(input.getAttribute('max'));
let num1 = new Cart(Number(input.value));
if (num1.num <= max) {
num1.num -= 1;
}
if (num1.num <= Cart.min) {
num1.num = Cart.min;
}
input.value = num1.num;
});
});
}
}
Cart.global();
// events
Cart.getBtn.addEventListener('click', function() {
Cart.insertEl();
Cart.plusFunc();
Cart.minusFunc();
});
<button type="button" id="get">get</button>
<main></main>
You're adding a new plus and a new minus listener to each element whenever a new element is appended. Have plusFunc and minusFunc only add to the newly created element instead:
class Cart {
static global() {
Cart.getBtn = document.getElementById('get');
Cart.main = document.getElementsByTagName('main')[0];
Cart.min = 1;
}
constructor(num) {
this.num = num;
}
static insertEl() {
const div = document.createElement('div');
div.innerHTML = `
<br>
<div>
<button type="button" class="minus">-</button>
<input type="number" min="1" max="20" value="1">
<button type="button" class="plus">+</button>
</div>
`;
Cart.main.appendChild(div);
return div;
}
static plusFunc(btn) {
btn.addEventListener('click', function(e) {
let input = e.target.previousElementSibling;
let max = Number(input.getAttribute('max'));
let num1 = new Cart(Number(input.value));
if (num1.num >= Cart.min) {
num1.num += 1;
}
if (num1.num >= max) {
num1.num = max;
}
input.value = num1.num;
});
}
static minusFunc(btn) {
btn.addEventListener('click', function(e) {
let input = e.target.nextElementSibling;
let max = Number(input.getAttribute('max'));
let num1 = new Cart(Number(input.value));
if (num1.num <= max) {
num1.num -= 1;
}
if (num1.num <= Cart.min) {
num1.num = Cart.min;
}
input.value = num1.num;
});
}
}
Cart.global();
// events
Cart.getBtn.addEventListener('click', function() {
const div = Cart.insertEl();
const [minus, plus] = div.querySelectorAll('button');
Cart.plusFunc(plus);
Cart.minusFunc(minus);
});
<button type="button" id="get">get</button>
<main></main>
But this quite a weird setup - why have a class that basically has nothing but static methods? Consider a plain object instead:
const Cart = {
getBtn: document.getElementById('get'),
main: document.querySelector('main'),
min: 1,
max: 20,
insertEl() {
const div = document.createElement('div');
div.innerHTML = `
<button type="button" class="minus">-</button>
<input type="number" min="1" max="20" value="1">
<button type="button" class="plus">+</button>
`;
this.main.insertAdjacentHTML('beforeend', '<br>');
this.main.appendChild(div);
return div;
}
}
Cart.getBtn.addEventListener('click', function() {
const div = Cart.insertEl();
const [minus, input, plus] = div.children;
minus.addEventListener('click', () => input.value = Math.max(Cart.min, input.value - 1));
plus.addEventListener('click', () => input.value = Math.min(Cart.max, Number(input.value) + 1));
});
<button type="button" id="get">get</button>
<main></main>

simple jquery dropdownfield update

I'm new to jQuery
I have a dropdown field and input field. Everytime I change the dropdown field, the value from the selected dropdown field needs to update in the total automatically.
The value only changes when i put something in the input field. I tested it with .change but it doesn't work
$(function() {
$('input').keyup(function() { // run anytime the value changes
var firstValue = parseFloat($('#id_turnover').val()) || 0; // get value of field
var secondValue = parseFloat($('#id_invoiced').val()) || 0; // convert it to a float
var thirdValue = parseFloat($('#id_collected').val()) || 0;
var fourthValue = parseFloat($('#id_otherfield').val()) || 0;
var total = firstValue + secondValue + thirdValue; // add them together
$('#added').html(total); // output it
$('#added2').html(total + fourthValue); // add them and output it
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="turnover">
<option value="20" id="id_turnover">kuzkit</option>
<option value="20" id="id_invoiced">testt</option>
<option value="20" id="id_collected">tetetessr</option>
<div id="container">Total<span style="clear:both;" id="added"></span>
<br>
</div>
<input type="text" id="id_otherfield" />
</select>
<div id="container2">Total + random field<span style="clear:both;" id="added2"></span>
<br>
</div>
Here is my fiddle
Add multiple events on multiple elements. Your closing </select> was wrong.
$('input, select').on('input change', function() {
// run anytime the value changes
updateTotals()
});
function updateTotals() {
var firstValue = parseFloat($('#id_turnover').val()) || 0; // get value of field
var secondValue = parseFloat($('#id_invoiced').val()) || 0; // convert it to a float
var thirdValue = parseFloat($('#id_collected').val()) || 0;
var fourthValue = parseFloat($('#id_otherfield').val()) || 0;
var total = firstValue + secondValue + thirdValue; // add them together
$('#added').text(total); // output it
$('#added2').text(total + fourthValue); // add them and output it
}
$('input, select').on('input change', function() { // run anytime the value changes
updateTotals()
});
function updateTotals() {
var firstValue = parseFloat($('#id_turnover').val()) || 0; // get value of field
var secondValue = parseFloat($('#id_invoiced').val()) || 0; // convert it to a float
var thirdValue = parseFloat($('#id_collected').val()) || 0;
var fourthValue = parseFloat($('#id_otherfield').val()) || 0;
var total = firstValue + secondValue + thirdValue; // add them together
$('#added').text(total); // output it
$('#added2').text(total + fourthValue); // add them and output it
}
* {
float: left;
clear: left;
margin: 10px 0;
}
#container {
clear: both;
margin: 10px 0;
}
#container2 {
clear: both;
margin: 10px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="turnover">
<option value="20" id="id_turnover">kuzkit</option>
<option value="20" id="id_invoiced">testt</option>
<option value="20" id="id_collected">tetetessr</option>
</select>
<div id="container">Total<span style="clear:both;" id="added"></span>
</div>
<input type="text" id="id_otherfield" />
<div id="container2">Total + random field<span style="clear:both;" id="added2"></span>
</div>

how to use javascript onkeyup for multiple ids at sametime

I have 2 html textbox for users to enter numbers. To sum those numbers, I am passing the values to JavaScript variable and after addition displaying the result to html div section
<div class="input-left"><span><input class="textbox" id="left" name="count" type="text" size="5" value="" /></span></div>
<div class="input-right"><span><input class="textbox" id="right" name="count" type="text" size="5" value="" /></span></div>
<div id="result"> </div>
javascript:
document.getElementById('left').onkeyup = function() {
var a = parseFloat(this.value);
}
document.getElementById('right').onkeyup = function() {
var b = a + parseFloat(this.value);
document.getElementById("result").innerHTML = b || 0 ;
}
But I have an issue with JavaScript. It not displaying the result. How to add both functions in same onkeyup function.
FIDDLE SETUP
Try this:
window.onload = function(){
var left = document.getElementById('left');
var right = document.getElementById('right');
var result = document.getElementById("result");
left.onkeyup = calc;
right.onkeyup = calc;
function calc() {
var a = parseFloat(left.value) || 0;
var b = parseFloat(right.value) || 0;
result.innerHTML = a + b ;
}
}
JSFiddle: http://fiddle.jshell.net/gYV8Z/3/
Update: To hide the result in case the sum equals zero , change the last line like this:
result.innerHTML = ( a + b ) || "";
JSFiddle: http://fiddle.jshell.net/gYV8Z/4/
document.getElementById('left').onkeyup = function() {
var a = parseFloat(this.value);
}
document.getElementById('right').onkeyup = function() {
var b = a + parseFloat(this.value);
document.getElementById("result").innerHTML = b || 0 ;
}
it your code, var a is local variable. make it global variable.
but i would use this code.
function add(){
return parseFloat(document.getElementById('left').value) + parseFloat(document.getElementById('right').value);
}
document.getElementById('left').onkeyup = function() {
document.getElementById("result").innerHTML = add();
}
document.getElementById('right').onkeyup = function() {
document.getElementById("result").innerHTML = add();
}

Categories