I am working on a little dice game, where the user can lock specific die. But I can't get it to work with if else statements. How do I "roll" the dice only where the checkboxes are unchecked?
const btnRoll = document.querySelector('.btn_roll');
btnRoll.addEventListener('click', () => {
roll();
});
function roll() {
const dice1 = document.querySelector('.dice1');
const dice2 = document.querySelector('.dice2');
const dice3 = document.querySelector('.dice3');
if (!document.getElementById('dice-1').checked) {
randomOne = Math.floor(Math.random() * 6) + 1;
dice1.src = `img/dice-${randomOne}.png`;
console.log(!document.getElementById('dice-1').checked);
} else if (!document.getElementById('dice-2').checked) {
randomTwo = Math.floor(Math.random() * 6) + 1;
dice2.src = `img/dice-${randomTwo}.png`;
} else if (!document.getElementById('dice-3').checked) {
randomThree = Math.floor(Math.random() * 6) + 1;
dice3.src = `img/dice-${randomThree}.png`;
} else {
console.log('no checkboxes are selected');
}
}
<form id="dices">
<input type="checkbox" id="dice-1" name="dice-1" value="dice-1" />
<img src="img/dice-5.png" alt="Dice" class="dice1" id="dice-1" />
<input type="checkbox" id="dice-2" name="dice-2" value="dice-2" />
<img src="img/dice-5.png" alt="Dice" class="dice2" id="dice-2" />
<input type="checkbox" id="dice-3" name="dice-3" value="dice-3" />
<img src="img/dice-5.png" alt="Dice" class="dice3" id="dice-3" />
<input type="checkbox" id="dice-4" name="dice-4" value="dice-4" /> 5.png" alt="Dice" class="dice6" id="dice-6" />
</form>
<br />
<button class="btn_roll">roll</button>
You are using "else-if" statements which effectively short-circuits your logic when one of them runs. Replace "else-if" with "if":s only.
(I replaced the last "else"-statement with an "if"-statement which is the negation of the other if-statements, since we can't do an else here.)
function roll() {
const dice1 = document.querySelector('.dice1');
const dice2 = document.querySelector('.dice2');
const dice3 = document.querySelector('.dice3');
const firstDiceChecked = document.getElementById('dice-1').checked
const secondDiceChecked = document.getElementById('dice-2').checked
const thirdDiceChecked = document.getElementById('dice-3').checked
if (!firstDiceChecked) {
randomOne = Math.floor(Math.random() * 6) + 1;
dice1.src = `img/dice-${randomOne}.png`;
console.log(!document.getElementById('dice-1').checked);
}
if (!secondDiceChecked) {
randomTwo = Math.floor(Math.random() * 6) + 1;
dice2.src = `img/dice-${randomTwo}.png`;
}
if (!thirdDiceChecked) {
randomThree = Math.floor(Math.random() * 6) + 1;
dice3.src = `img/dice-${randomThree}.png`;
}
if (!firstDiceChecked && !secondDiceChecked && !thirdDiceChecked) {
console.log('no checkboxes are selected');
}
}
I would use a div with a background image instead of swapping the src of an actual image object.
You can simplify this with a loop and targeting the parent of the checkbox to get the die image.
document.querySelector('.btn-roll').addEventListener('click', rollDice);
function rollDice(e) {
let checked = document.querySelectorAll('#dice .die-wrapper input:checked');
Array.from(checked).forEach(cb => {
let die = cb.parentElement.querySelector('.die');
let roll = getRandomIntInclusive(1, 6);
die.className = 'die die-' + roll;
die.setAttribute('data-roll', roll);
});
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random#Getting_a_random_integer_between_two_values_inclusive
function getRandomIntInclusive(min, max) {
if (arguments.length === 1) { max = min; min = 0; }
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
.die-wrapper {
display: inline-block;
}
.die {
display: inline-block;
width: 32px;
height: 32px;
background-position: center;
background-repeat: no-repeat;
}
.die-1 { background-image: url('https://place-hold.it/32x32/f00/000.png&bold&text=1'); }
.die-2 { background-image: url('https://place-hold.it/32x32/f00/000.png&bold&text=2'); }
.die-3 { background-image: url('https://place-hold.it/32x32/f00/000.png&bold&text=3'); }
.die-4 { background-image: url('https://place-hold.it/32x32/f00/000.png&bold&text=4'); }
.die-5 { background-image: url('https://place-hold.it/32x32/f00/000.png&bold&text=5'); }
.die-6 { background-image: url('https://place-hold.it/32x32/f00/000.png&bold&text=6'); }
<form id="dice">
<div class="die-wrapper">
<input type="checkbox" name="die-1" value="dice-1" />
<div class="die die-1"></div>
</div>
<div class="die-wrapper">
<input type="checkbox" name="die-2" value="dice-2" />
<div class="die die-1"></div>
</div>
<div class="die-wrapper">
<input type="checkbox" name="die-3" value="dice-3" />
<div class="die die-1"></div>
</div>
</form>
<br />
<button class="btn-roll">Roll</button>
Using Unicode glyphs for display of die faces...
document.querySelector('.btn-roll').addEventListener('click', rollDice);
function rollDice(e) {
let checked = document.querySelectorAll('#dice .die-wrapper input:checked');
Array.from(checked).forEach(cb => {
let die = cb.parentElement.querySelector('.die');
let roll = getRandomIntInclusive(1, 6);
die.className = 'die die-' + roll;
die.setAttribute('data-roll', roll);
});
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random#Getting_a_random_integer_between_two_values_inclusive
function getRandomIntInclusive(min, max) {
if (arguments.length === 1) {
max = min;
min = 0;
}
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
.die-wrapper {
display: inline-block;
}
.die {
display: inline-block;
height: 2em;
}
.die::after {
font-size: 3em;
line-height: 0.75em;
}
.die-1::after { content: '\2680'; }
.die-2::after { content: '\2681'; }
.die-3::after { content: '\2682'; }
.die-4::after { content: '\2683'; }
.die-5::after { content: '\2684'; }
.die-6::after { content: '\2685'; }
<form id="dice">
<div class="die-wrapper">
<input type="checkbox" name="die-1" value="dice-1" />
<div class="die die-1"></div>
</div>
<div class="die-wrapper">
<input type="checkbox" name="die-2" value="dice-2" />
<div class="die die-1"></div>
</div>
<div class="die-wrapper">
<input type="checkbox" name="die-3" value="dice-3" />
<div class="die die-1"></div>
</div>
</form>
<br />
<button class="btn-roll">Roll</button>
const checkboxes = [
document.getElementById("dice-1")
document.getElementById("dice-2")
document.getElementById("dice-3")
document.getElementById("dice-4")
document.getElementById("dice-5")
];
let allChecked = true;
for (const checkbox of checkboxes) {
if (!checkbox.checked) allChecked = false;
}
if (allChecked) {
roll();
}
Related
I am kind of having trouble on making my clear function works on my calculator
This is my HTML:
<input type="button" id="result" value="C" onClick="clr()">
<input type="button" name="greater" value="<" onClick="calcNumbers(greater.value)">
<input type="button" name="divb" value="/" onClick="calcNumbers(divb.value)">
<input type="button" name="mulb" value="*" onClick="calcNumbers(mulb.value)">
and this is my JavaScript
function calcNumbers(result) {
form.displayResult.value = form.displayResult.value + result;
}
Wrap all the input fields inside form tag or div tag and give id to that tag, ... and in script tag add function and rest it as document.getElementById("myForm").reset();
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script language="javascript" type="text/javascript">
function Add() {
var x, y, txtResult;
x = document.getElementById('txtFirst').value;
y = document.getElementById('txtSecond').value;
if (x == " " || y == "") {
alert("Please enter FirstValue and SecondValue");
}
else{
var txtResult = +x + +y;
document.getElementById('txtResult').innerHTML = "Result: " + txtResult;
}
}
function Sub() {
var x, y, txtResult;
x = document.getElementById('txtFirst').value;
y = document.getElementById('txtSecond').value;
if (x == " " || y == "") {
alert("Please enter FirstValue and SecondValue");
} else {
var txtResult = +x - +y;
document.getElementById('txtResult').innerHTML = "Result: " + txtResult;
}
}
function Mul() {
var x, y, txtResult;
x = document.getElementById('txtFirst').value;
y = document.getElementById('txtSecond').value;
if (x == " " || y == "") {
alert("Please enter FirstValue and SecondValue");
} else {
var txtResult = +x * +y;
document.getElementById('txtResult').innerHTML = "Result: " + txtResult;
}
}
function Div() {
var x, y, txtResult;
x = document.getElementById('txtFirst').value;
y = document.getElementById('txtSecond').value;
if (x == " " || y == "") {
alert("Please enter FirstValue and SecondValue");
}
else if (y != 0) {
var txtResult = +x / +y;
}
else {
alert("Second Number Should not be Zero");
}
document.getElementById('txtResult').innerHTML = "Result: " + txtResult;
}
function Clear() {
document.getElementById('txtFirst').value = "";
document.getElementById('txtSecond').value = "";
document.getElementById('txtResult').value = "";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<label> FirstNumber :</label><br />
<input id="txtFirst" type="text" /><br />
<label> Second Number :</label><br />
<input id="txtSecond" type="text" /><br />
<label id="txtResult"></label><br />
<input id="btnAdd" type="button" value="ADD" onclick="Add()"/>
<input id="btnSub" type="button" value="SUB" onclick="Sub()"/><br />
<input id="btnMul" type="button" value="MUL" onclick="Mul()"/>
<input id="btnDiv" type="button" value="DIV" onclick="Div()"/>
<input id="btnClear" type="button" value="Clear" onclick="Clear()"/>
</div>
</form>
</body>
</html>
Calculator image
You can clear the text by setting the value to an empty string.
const form = document.querySelector('.calculator > form');
const handleMemoryClear = (v) => {
const disp = form.querySelector('.display');
disp.value = '';
};
const handleMemoryRecall = (v) => console.log('Implement MEMORY_RECALL');
const handleMemoryAdd = (v) => console.log('Implement MEMORY_ADD');
const handleMemoryRemove = (v) => console.log('Implement MEMORY_REMOVE');
const handleOpAdd = (v) => console.log('Implement OP_ADD');
const handleOpSub = (v) => console.log('Implement OP_SUB');
const handleOpMul = (v) => console.log('Implement OP_MUL');
const handleOpDiv = (v) => console.log('Implement OP_DIV');
const handleOpEval = (v) => console.log('Implement OP_EVAL');
const handleTypeIn = (v) => {
const disp = form.querySelector('.display');
disp.value += v;
};
const handleTypeOp = (v) => {
switch (v) {
case '+': return handleOpAdd();
case '-': return handleOpSub();
case '×': return handleOpMul();
case '÷': return handleOpDiv();
case '=': return handleOpEval();
}
}
const handleTypeFn = (v) => {
switch (v) {
case 'MC': return handleMemoryClear();
case 'MR': return handleMemoryRecall();
case 'M+': return handleMemoryAdd();
case 'M-': return handleMemoryRemove();
}
}
const handleButtonPress = (button, type) => {
switch (type) {
case 'in': return handleTypeIn(button.textContent);
case 'op': return handleTypeOp(button.textContent);
case 'fn': return handleTypeFn(button.textContent);
}
};
const ignoreSubmission = e => e.preventDefault();
const handleFormInput = e => {
if (e.target instanceof HTMLButtonElement && e.target.dataset.type) {
handleButtonPress(e.target, e.target.dataset.type);
}
};
form.addEventListener('submit', ignoreSubmission);
form.addEventListener('click', handleFormInput);
:root {
--root-bg: #222;
--root-fg: #EEE;
--calc-bg: #444;
--calc-border: #888;
--calc-disp-bg: #333;
--calc-disp-fg: #EEE;
--calc-btn-bg: #444;
--calc-btn-fg: #EEE;
--calc-btn-hover-bg: #888;
}
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
body {
display: flex;
align-items: center;
justify-content: center;
background: var(--root-bg);
color: var(--root-fg);
}
.calculator {
display: flex;
padding: 0.25em;
background: var(--calc-bg);
border: thin solid var(--calc-border);
align-items: center;
}
.calc-input {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-gap: 0.25em;
}
.calc-input > .display {
grid-column-start: 1;
grid-column-end: 5;
grid-row-start: 1;
grid-row-end: 1;
font-size: 1.5em;
background: var(--calc-disp-bg);
border: thin solid var(--calc-border);
color: var(--calc-disp-fg);
font-family: monospace;
text-align: right;
padding: 0.25em;
}
.calc-key {
display: flex;
align-items: center;
justify-content: center;
font-size: 1.125em;
font-weight: bold;
border: thin solid var(--calc-border);
background: var(--calc-btn-bg);
color: var(--calc-btn-fg);
padding: 0.25em 0;
cursor: pointer;
}
.calc-key:hover {
cursor: pointer;
background: var(--calc-btn-hover-bg);
}
.calc-key[data-type="fn"] {
background: #06D;
}
.calc-key[data-type="fn"]:hover {
background: #08F;
}
.calc-key[data-type="op"] {
background: #D60;
}
.calc-key[data-type="op"]:hover {
background: #F80;
}
<div class="calculator">
<form class="calc-input">
<input type="text" class="display" placeholder="0" />
<button class="calc-key" data-type="fn">MC</button>
<button class="calc-key" data-type="fn">M+</button>
<button class="calc-key" data-type="fn">M-</button>
<button class="calc-key" data-type="fn">MR</button>
<button class="calc-key" data-type="in">7</button>
<button class="calc-key" data-type="in">8</button>
<button class="calc-key" data-type="in">9</button>
<button class="calc-key" data-type="op">÷</button>
<button class="calc-key" data-type="in">4</button>
<button class="calc-key" data-type="in">5</button>
<button class="calc-key" data-type="in">6</button>
<button class="calc-key" data-type="op">×</button>
<button class="calc-key" data-type="in">1</button>
<button class="calc-key" data-type="in">2</button>
<button class="calc-key" data-type="in">3</button>
<button class="calc-key" data-type="op">-</button>
<button class="calc-key" data-type="in">0</button>
<button class="calc-key" data-type="in">.</button>
<button class="calc-key" data-type="op">=</button>
<button class="calc-key" data-type="op">+</button>
</form>
</div>
Below it's my code with a quiz of 4 questions and with a "Submit" button in the last question and I tried to add some code that on Submit it will show an alert with the results of the quiz about how many questions I got correct.
But there are some errors with my code that when I press Submit it doesn't show results of the quiz and it still shows me "Select an option", even that I've selected an option from the question and I've added an if statement to Submit button so it will check if any option is selected or not, but even If I select any option it still shows me that alert ?
let question1 = document.getElementById('pytja1');
let question2 = document.getElementById('pytja2');
let question3 = document.getElementById('pytja3');
let question4 = document.getElementById('pytja4');
let result = document.getElementById('bot-submit');
let nextButtons = document.querySelectorAll('.bot');
for (let i = 0; i < nextButtons.length; i++) {
let nextQuestion = nextButtons[i];
nextQuestion.onclick = function() {
if (validateForm(i + 1)) {
switchToNextQuestion(this);
}
}
}
function switchToNextQuestion(nextQuestion) {
let parentId = nextQuestion.parentNode.id;
if (parentId === 'pytja1') {
question1.style.display = 'none';
question2.style.display = 'block';
} else if (parentId === 'pytja2') {
question2.style.display = 'none';
question3.style.display = 'block';
} else if (parentId === 'pytja3') {
question3.style.display = 'none';
question4.style.display = 'block';
}
}
function validateForm(elementNumber) { // elementnumber gets radio name from multiple questions
let radios = document.getElementsByName("q" + elementNumber);
let formValid = false;
let i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) formValid = true;
i++;
}
if (!formValid) alert("Select one option");
return formValid;
}
let questions = [{
question: "I am a ?",
userAnswers: ["Male", "Female", "Other"],
correctAnswers: 0,
},
{
question: "Football has letters ?",
userAnswers: [8, 5, 6],
correctAnswers: 0,
},
{
question: "VW stands for ?",
userAnswers: ["BMW", "Volkswagen", "Audi"],
correctAnswers: 1,
},
{
question: "What year is it ?",
userAnswers: [2017, 2015, 2019],
correctAnswers: 2,
}
];
function submitAnswer(elementNumber) {
let radios = document.getElementsByName("q" + elementNumber);
let formValid = false;
let i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) formValid = true;
i++;
}
if (!formValid) alert("Select one option");
return formValid;
for (i = 0; i < questions.length; i++) {
let correctAnswerIndex = questions[i].correctAnswers;
if (correctAnswerIndex === userAnswers[i]) {
score++;
}
}
if (score != total) {
alert("You got " + score + " out " + total)
}
if (score === total) {
alert("Congratulation your score " + score + " out of " + total);
}
let results = document.getElementById('results')
alert("you")
}
document.getElementById("bot-submit").addEventListener("click",
function(e) {
e.preventDefault();
})
form {
width: 100%;
position: relative;
float: left;
padding-top: 50px;
}
.quiz {
margin: 0px auto;
width: 250px;
height: 100px;
position: absolute;
top: 60px;
left: 42%;
}
.quest1,
.quest2,
.quest3,
.quest4 {
background-color: cadetblue;
font-size: 22px;
}
.questions1 {
margin-left: 28px;
background-color: cyan;
width: 220px;
padding: 10px;
font-size: 20px;
}
.questions2 {
background-color: red;
}
.questions3 {
background-color: greenyellow;
}
.questions4 {
background-color: olivedrab;
}
.bot {
margin-top: 10px;
}
#pytja2,
#pytja3,
#pytja4 {
margin-left: 28px;
display: none;
width: 220px;
padding: 10px;
font-size: 20px;
}
<form id="quiz-form">
<div di="results"></div>
<div class="quiz">
<div id="pytja1" class="questions1">
<span class="quest1">I am a ?</span><br/>
<input type="radio" name="q1" value="male" id="correct"> Male<br/>
<input type="radio" name="q1" value="female" id="correct2"> Female<br/>
<input type="radio" name="q1" value="other" id="correct3"> Other<br/>
<input class="bot" type="button" value="Next" "/>
</div>
<div id="pytja2 " class="questions2 ">
<span class="quest2 ">Football has letters ?</span><br/>
<input type="radio " name="q2 " value="8 " class="correct "> 8<br/>
<input type="radio " name="q2 " value="5 "> 5<br/>
<input type="radio " name="q2 " value="6 "> 6<br/>
<input class="bot " type="button " value="Next ""/>
</div>
<div id="pytja3" class="questions3">
<span class="quest3">VW stands for ?</span><br/>
<input type="radio" name="q3" value="BMW" /> BMW <br/>
<input type="radio" name="q3" value="Volkswagen" class="correct" /> Volkswagen<br/>
<input type="radio" name="q3" value="Audi" /> Audi<br/>
<input class="bot" type="button" value="Next" "/>
</div>
<div id="pytja4 " class="questions4 ">
<span class="quest4 ">What year we are ?</span><br/>
<input type="radio " name="q4 " value="2017 " /> 2017<br/>
<input type="radio " name="q4 " value="2015 " /> 2015<br/>
<input type="radio " name="q4 " value="2019 " class="correct " /> 2019<br/>
<input id="bot-submit " type="submit " value="Submit " onclick="submitAnswer(); "/>
</div>
</div>
</form>
As mentioned above, your code has some errors but I have written snippets that will achieve your aim with shorter syntax.
//Javascript code
let questionss = [{
question: "I am a ?",
options: ["Male", "Female", "Other"],
correctAnswers: 'Male',
},
{
question: "Football has letters ?",
options: [8, 5, 6],
correctAnswers: 8,
},
{
question: "VW stands for ?",
options: ["BMW", "Volkswagen", "Audi"],
correctAnswers: 'Volkswagen',
},
{
question: "What year is it ?",
options: [2017, 2015, 2019],
correctAnswers: 2019,
}
];
let questionText = document.getElementById('cd-questions');
let optiontext = document.querySelectorAll('.optiontext');
let options = document.querySelectorAll('.options');
let nextBtn = document.getElementById('next-btn');
let currentQuestion = 0;
var score = 0;
var checkedStatus = false;
setQuestion(currentQuestion); // set default question
nextBtn.addEventListener('click', e => {
e.preventDefault();
if (valForm()) setQuestion(currentQuestion); //validates and next question
});
function setQuestion(currentQuestion) {
questionText.innerText = questionss[currentQuestion].question; //set current question to the DOM
for (let i = 0; i < 3; i++) {
options[i].value = questionss[currentQuestion].options[i]; //set options value for current question
optiontext[i].innerText = questionss[currentQuestion].options[i]; //set options for current question
}
}
function valForm() {
for (let i = 0; i < 3; i++) {
if (options[i].checked) {
let userans = options[i].value;
if (questionss[currentQuestion].correctAnswers == userans) {
score++;
}
options[i].checked = false;
if (currentQuestion < questionss.length - 1) {
currentQuestion++;
if (currentQuestion == questionss.length - 1) {
nextBtn.innerText = 'Submit';
}
} else {
alert('Your total score is ' + score);
currentQuestion = 0;
nextBtn.innerText = 'Start';
}
return true;
}
}
if (checkedStatus == false) {
alert('please choose an answer');
setQuestion(currentQuestion);
}
return false;
}
<form>
<div id="cd-questions"></div>
<input class="options" name="answer" type="radio" />
<span class="optiontext"></span>
<input class="options" name="answer" type="radio" />
<span class="optiontext"></span>
<input class="options" name="answer" type="radio" />
<span class="optiontext"></span>
<div>
<button id="next-btn">Next</button>
</div>
</form>
I'm happy it worked. I want to believe your other question is from the second loop.
for (let i = 0; i < 3; i++) {
if (options[i].checked) { //iterates through the radio buttons for the checked option
let userans = options[i].value; // get the value of the checked
if (questionss[currentQuestion].correctAnswers == userans) {
score++; //increment score by 1 if the chosen answer is the correct answer
}
options[i].checked = false; //reset button to avoid next question being checked by
default.
if (currentQuestion < questionss.length - 1) {
currentQuestion++; // increment current question index
if (currentQuestion == questionss.length - 1) {
nextBtn.innerText = 'Submit'; // Changed submit button text if it's the last question.
}
} else {
alert('Your total score is ' + score);
currentQuestion = 0;
nextBtn.innerText = 'Start';
}
return true; // return true which was tested when the function was involked before nexting the question.
}
}
I hope that helps.
I have 2 input with the class name .ValueNextYear who must have always the same value. The probleme is that, it don't have the same value in real time.
When I edit the first .ValueNextYear input who have 150 in value the second input ValueNextYear must have the same value but is not. If I enter 15000 in the first input ValueNextYear the second contain 1500.
Also for calculate the value of #EstimateAmountReceived input I need to have a real value in .ValueNextYear for have a good result.
(Look on NextYear() function)
Any help is welcome.
Sorry for my bad english
Link with code
var AmountNextYear = (value1, value2) => {
if (value1 >= 1 && value1 < 20) {
return value2 += 10;
} else if (value1 >= 20 && value1 < 50) {
return value2 += 20;
} else if (value1 >= 50 && value1 < 80) {
return value2 += 30;
} else if (value1 >= 80 && value1 < 100) {
return value2 += 40;
} else if (value1 >= 100 && value1 < 150) {
return value2 += 50;
} else if (value1 >= 150 && value1 < 300) {
return value2 += 60;
} else {
return value2;
}
};
var RealPaid = (value) => {
let RealPaidValue = value - value * 66 / 100;
return parseFloat(RealPaidValue).toFixed(2);
};
var TaxDeduction = (value) => {
let TaxDeductionValue = value * 66 / 100;
return parseFloat(TaxDeductionValue).toFixed(2);
};
var DownPayment = (value) => {
let DownPayment = value * 60 / 100;
return parseFloat(DownPayment).toFixed(2);
};
var DownPaymentInCompToLastYear = (value1, value2) => {
let DownPaymentInCompToLastYear = value1 * 66 / 100 - value2;
return parseFloat(DownPaymentInCompToLastYear).toFixed(2);
};
var checkSiEstIdentique = (ValueNextYear) => {
if (ValueNextYear != document.querySelectorAll(".ValueNextYear").value) {
return ValueNextYear = document.querySelectorAll(".ValueNextYear").value;
}
};
var main = () => {
var valueDonation = document.getElementById("valeurDon").value.replace(",", ".");
document.getElementById("Deduction").value = TaxDeduction(valueDonation).replace(".", ",");
var PostValueDonation = Math.ceil(valueDonation / 5) * 5;
for (var i = document.querySelectorAll(".ValueNextYear").length - 1; i >= 0; i--) {
document.querySelectorAll(".ValueNextYear")[i].value = AmountNextYear(valueDonation, PostValueDonation);
}
var ValueNextYear = AmountNextYear(valueDonation, PostValueDonation);
checkSiEstIdentique(document.querySelectorAll(".ValueNextYear")[0].value);
document.getElementById("DownPayment").value = DownPayment(TaxDeduction(valueDonation)).replace(".", ",");
var DownPay = DownPayment(TaxDeduction(valueDonation));
document.getElementById("EstimateAmountReceived").value = DownPaymentInCompToLastYear(ValueNextYear, DownPay).replace(".", ",");
document.getElementById("formGroupExampleInput").value = TaxDeduction(ValueNextYear).replace(".", ",");
document.getElementById("RealPaidValue").value = RealPaid(ValueNextYear).replace(".", ",");
document.querySelectorAll(".ValueNextYear")[0].addEventListener("keydown", function (event) {
NextYear(DownPay);
});
};
var NextYear = (DownPay) => {
console.log("ValueNextYear", document.querySelectorAll(".ValueNextYear")[0].value);
document.querySelectorAll(".ValueNextYear")[1].value = document.querySelectorAll(".ValueNextYear")[0].value;
console.log("EstimateAmountReceived", document.getElementById("EstimateAmountReceived").value);
// document.getElementById("EstimateAmountReceived").value = DownPaymentInCompToLastYear(document.querySelectorAll(".ValueNextYear")[0].value, DownPay )
};
document.addEventListener("DOMContentLoaded", function (event) {
main()
});
<div style="width: 80%; margin: auto;">
<form>
<div style="display: flex; justify-content: space-between;">
<label for="formGroupExampleInput">En 2017, vous avez donné :</label>
<input type="text" class="" id="valeurDon" onkeyup="main()" value="100">
</div>
<div style="display: flex; justify-content: space-between;">
<label for="formGroupExampleInput2">Votre déduction fiscale sur votre don 2017</label>
<input type="text" id="Deduction" disabled>
</div>
<div style="display: flex; justify-content: space-between;">
<label for="formGroupExampleInput2">Pour un don 2018 de :</label>
<input type="text" class="ValueNextYear">
</div>
<div style="display: flex; justify-content: space-between;">
<label for="formGroupExampleInput">Vous recevrez un acompte des impôts en janvier 2019 de :</label>
<input type="text" id="DownPayment" disabled>
</div>
<div style="display: flex; justify-content: space-between;">
<label for="formGroupExampleInput2">Vous percevrez en juillet 2019 un solde de :</label>
<input type="text" id="EstimateAmountReceived" disabled>
</div>
<div style="display: flex; justify-content: space-between;">
<label for="formGroupExampleInput">Montant du don que vous souhaitez effectuer en 2018</label>
<input type="text" class="ValueNextYear" disabled>
</div>
<div style="display: flex; justify-content: space-between;">
<label for="formGroupExampleInput2">Montant total de votre déduction fiscale 2018</label>
<input type="text" id="formGroupExampleInput" disabled>
</div>
<div style="display: flex; justify-content: space-between;">
<label for="formGroupExampleInput">Coût réel de vos dons 2018</label>
<input type="text" id="RealPaidValue" disabled>
</div>
</form>
</div>
Change the keydown to keyup
In the main function, change:
document.querySelectorAll(".ValueNextYear")[0].addEventListener("keydown", function (event) {
NextYear(DownPay);
});
To:
document.querySelectorAll(".ValueNextYear")[0].addEventListener("keyup", function (event) {
NextYear(DownPay);
});
See your code working here:
https://codepen.io/KenzDozz/pen/pOYdRx
As pointed by #enxaneta if I change keydown event by input event it works.
document.querySelectorAll(".ValueNextYear")[0].addEventListener('input', function(event){
NextYear(DownPay)
} );
And as pointed by #KENZiE it works too if I replace keydown event by keyup event.
document.querySelectorAll(".ValueNextYear")[0].addEventListener('keyup', function(event){
NextYear(DownPay)
} );
<!DOCTYPE html>
<html>
<body>
<p>A function is triggered when the user is pressing a key in the input field.</p>
<input id="one" type="text" value="" onKeyUp="myFunction()">
<input id="two" type="text" value="" >
<script>
function myFunction() {
document.getElementById("two").value = document.getElementById("one").value;
}
</script>
</body>
</html>
I built a WooCommerce configurator on my landingpage, but unfortuantely it doesn't work. Console shows problem with JS code because of .hasclass() which I just don't get - can anyone help me?
Thanks a lot!
HTML:
<div id="amounts">
<button type="button" class="amount-button dreiriegel" value="6,50€" name="7,47€">
<h2>3 Natural Energy-Riegel</h2>
</button>
<button type="button" class="amount-button zwoelfriegel" id="selected" value="23,88€" name="29,88">
<h2>12 Natural Energy-Riegel</h2>
<span>Du sparst xyz</span>
</button>
<button type="button" class="amount-button vierundzwanzigriegel" value="44,90€" name="59,76€">
<h2>24 Natural Energy-Riegel</h2>
<span>Du sparst yz</span>
</button>
</div>
<div id="offer-price"></div>
<div id="normal-price"></div>
<div id="input_div">
<input type="button" value="-" id="moins" onclick="minus()">
<div value="1" id="count">1</div>
<input type="button" value="+" id="plus" onclick="plus()">
</div>
<form id=“bestell-button" action="/cart/?add-to-cart=294&variation_id=299&quantity=1&attribute_pa_variante=12-riegel" method="POST">
<input type="submit" value="Jetzt bestellen">
</form>
CSS:
#selected {
background-color: green;
}
.amount-button {
width: 100%;
}
.amount-button:hover {
cursor: pointer;
}
.amount-button:hover {
background: #DDD;
}
JavaScript:
jQuery(document).ready(function () {
var selected_oprice = jQuery('#selected').val();
jQuery('#offer-price').html(selected_oprice);
var selected_nprice = jQuery('#selected').attr("name");
jQuery('#normal-price').html(selected_nprice);
});
jQuery(function($) {
$('.amount-button').click(function() {
$('.amount-button').not(this).removeAttr('id', 'selected');
$(this).attr('id', 'selected');
var selected_oprice = jQuery('#selected').val();
jQuery('#offer-price').html(selected_oprice);
var selected_nprice = jQuery('#selected').attr("name");
jQuery('#normal-price').html(selected_nprice);
});
});
var count = 1;
var countEl = document.getElementById("count");
function plus(){
count++;
countEl.value = count;
countEl.innerHTML = count;
}
function minus(){
if (count > 1) {
count--;
countEl.value = count;
countEl.innerHTML = count;
}
}
function getVariation(){
var dieses=jQuery(this);
if (dieses.hasClass("dreiriegel")) {
return 297;
}
else if (dieses.hasClass("zwoelfriegel")) {
return 299;
}
else if (dieses.hasClass("vierundzwanzigriegel")) {
return 300;
}
}
function getAttribute(){
var jenes=jQuery(this);
if (jenes.hasClass("dreiriegel")) {
return 3-riegel;
}
else if (jenes.hasClass("zwoelfriegel")) {
return 12-riegel;
}
else if (jenes.hasClass("vierundzwanzigriegel")) {
return 24-riegel;
}
}
function getLink(){
var href=window.location;
var amount=document.getElementById("#count").value;
var attribute=jQuery("#selected").getVariation();
var variante=jQuery("#selected").getAttribute();
href=href+"cart/?add-to-cart=294&variation_id="+variante+"&quantity="+amount+"&attribute_pa_variante="+attribute;
return href;
}
I'm writing an <input type="number"> with - and + button for an ecommerce cart.
The structure of each group is:
1x <button class="minus" data-prod="prod_id_int">
1x <input type="number" id="prod_id_int">
1x <button class="plus" data-prod="prod_id_int">
What I'm trying to do now is disabling the button - if the value of the input type number is < 1.
To achieve it, based on my script, I have to disable not the general <button class="minus"> but the specific <button class="minus" data-prod="prod_id_int">.
I tried this
$(buttonClass).data('prod', dataProd).prop('disabled', true);
and it actually prevents the quantity from being < 1 BUT it doesn't really add the property disabled to the button. I'm not sure, then, that it's the right way. Can someone explain me how to achieve it?
Here the working snippet
$(document).ready(function() {
$('button').on('click', function() {
var buttonClass = $(this).attr('class');
//console.log(buttonClass);
var buttonID = $(this).attr('id');
//console.log(buttonID);
var dataProd = $(this).data('prod');
var inputToChange = $('#' + dataProd);
var inputToChangeValue = $('#' + dataProd).val();
if (buttonClass == 'minus') {
var newValue = parseInt(inputToChangeValue) - parseInt(1);
if (newValue < 1) {
$(buttonClass).data('prod', dataProd).prop('disabled', true);
//$(buttonClass).data('prod="' + dataProd + '"').prop('disabled', true);
//$(buttonClass + '.[data-prod="' + dataProd + '"]').attr(disabled=disabled); //.prop('disabled', true)
//alert('NOPE');
} else {
$('#' + dataProd).val(newValue);
//console.log(inputToChangeValue);
}
} else if (buttonClass == 'plus') {
var newValue = parseInt(inputToChangeValue) + parseInt(1);
if (newValue > 99) {
alert('NOPPPPEE');
} else {
$('#' + dataProd).val(newValue);
console.log(inputToChangeValue);
}
}
});
});
.plus,
.minus {
width: 1.5%;
height: auto;
background-color: #EF1B1F;
border-radius: 50%;
text-align: center;
display: inline-block;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="minus" data-prod="23">-</button>
<input type="number" class="qta" id="23" value="5">
<button class="plus" data-prod="23">+</button>
<br>
<button class="minus" data-prod="90">-</button>
<input type="number" class="qta" id="90" value="62">
<button class="plus" data-prod="90">+</button>
Here is solution.
$('.'+buttonClass).data('prod', dataProd).prop('disabled', true);
All you need is to concatenate . symbol to your class.
buttonClass returns only the className, such as minus and you need jquery selector, like this: $('.minus')
Also, I recommend you to use this: var newValue = --inputToChangeValue; for a simply way to decrement value, instead var newValue = parseInt(inputToChangeValue) - parseInt(1);
$(document).ready(function() {
$('button').on('click', function() {
var buttonClass = $(this).attr('class');
//console.log(buttonClass);
var buttonID = $(this).attr('id');
//console.log(buttonID);
var dataProd = $(this).data('prod');
var inputToChange = $('#' + dataProd);
var inputToChangeValue = $('#' + dataProd).val();
if (buttonClass == 'minus') {
var newValue = --inputToChangeValue;
if (newValue < 1) {
$('.'+buttonClass).filter(function() {
return $(this).data("prod") == dataProd
}).prop('disabled', true);
//$(buttonClass).data('prod="' + dataProd + '"').prop('disabled', true);
//$(buttonClass + '.[data-prod="' + dataProd + '"]').attr(disabled=disabled); //.prop('disabled', true)
//alert('NOPE');
} else {
$('#' + dataProd).val(newValue);
//console.log(inputToChangeValue);
}
} else if (buttonClass == 'plus') {
var newValue = parseInt(inputToChangeValue) + parseInt(1);
$('.minus').filter(function() {
return $(this).data("prod") == dataProd
}).prop('disabled', false);
if (newValue > 99) {
alert('NOPPPPEE');
} else {
$('#' + dataProd).val(newValue);
console.log(inputToChangeValue);
}
}
});
});
.plus,
.minus {
width: 10%;
height: auto;
background-color: #EF1B1F;
border-radius: 50%;
text-align: center;
display: inline-block;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="minus" data-prod="23">-</button>
<input type="number" class="qta" id="23" value="5">
<button class="plus" data-prod="23">+</button>
<br>
<button class="minus" data-prod="90">-</button>
<input type="number" class="qta" id="90" value="12">
<button class="plus" data-prod="90">+</button>