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>
Related
Im trying to do simple calculation for the fee ,but its doesn't work ,there's no error in the code. Did I miss something in the script ?
<script type="text/javascript">
var bwm = 7.9;
var bswk = 14;
var bsbh = 15;
var wm = 2;
var swk = 11;
var sbh = 12;
var kilo, overkilo, f;
var s = document.getElementById('place');
var place = s.options[s.selectedIndex].value;
var k = document.getElementById('kilo').value;
var tot;
function quote() {
f = document.getElementById('theform');
f.reset();
document.getElementById('calc').onclick = function() {
if (place == 'swk') {
(k * swk) + bswk = tot;
} else if (place == 'sbh') {
(k * sbh) + bsbh = tot;
} else {
(k * wm) + bwm = tot;
}
document.getElementById('tot').value = 'RM ' + parseFloat;
}
}
</script>
<form id="theform" action="#">
<div>
<label for="place">Choose Destination :</label>
<select id="place" onChange="quote()">
<option value="swk">Sarawak</option>
<option value="sbh">Sabah</option>
<option value="wm">WestMalaysia</option>
</select>
</div>
<div>
<label for="kilo">Amount of KG :</label>
<input id="kilo" type="text">
</div>
<div>
<label>Total :</label>
<input id="tot" type="text" readonly="readonly">
</div>
<div>
<label></label>
<input id="calc" type="button" value="calculate">
<input id="r" type="reset" value="clear">
</div>
</form>
The clear works fine ,but the calculate button won't work even i have input the KG and select a option to calculate .
You need to move the definition of the click handler outside of the change handler, unless the click handler would be defined only when an option changes and also it would be defined on every option change which is unnecessary.
Grab all the required values inside the click handler otherwise you would not have the updated values.
And you also need to set the selected index after resetting the form otherwise the change of option would not be visible.
const
bwm = 7.9,
bswk = 14,
bsbh = 15,
wm = 2,
swk = 11,
sbh = 12;
function quote(e) {
const selIndex = e.target.selectedIndex;
document.getElementById("theform").reset();
document.getElementById("place").selectedIndex = selIndex;
}
document.getElementById("calc").onclick = function () {
const select = document.getElementById("place");
const place = select.options[select.selectedIndex].value;
const k = document.getElementById("kilo").value;
if (!k) {
return;
}
let tot;
if (place === "swk") {
tot = k * swk + bswk;
} else if (place === "sbh") {
tot = k * sbh + bsbh;
} else {
tot = k * wm + bwm;
}
document.getElementById("tot").value = "RM " + tot;
};
<form id="theform" action="#">
<div>
<label for="place">Choose Destination :</label>
<select id="place" onChange="quote(event)">
<option value="swk">Sarawak</option>
<option value="sbh">Sabah</option>
<option value="wm">WestMalaysia</option>
</select>
</div>
<div>
<label for="kilo">Amount of KG :</label>
<input id="kilo" type="text">
</div>
<div>
<label>Total :</label>
<input id="tot" type="text" readonly="readonly">
</div>
<div>
<label></label>
<input id="calc" type="button" value="calculate">
<input id="r" type="reset" value="clear">
</div>
</form>
Instead of resetting the form you could also update the calculated value every time the option changes.
const
bwm = 7.9,
bswk = 14,
bsbh = 15,
wm = 2,
swk = 11,
sbh = 12;
document.getElementById("calc").onclick = handleClick;
function handleClick() {
const select = document.getElementById("place");
const place = select.options[select.selectedIndex].value;
const k = document.getElementById("kilo").value;
if (!k) {
return;
}
let tot;
if (place === "swk") {
tot = k * 10 + 10;
} else if (place === "sbh") {
tot = k * sbh + bsbh;
} else {
tot = k * wm + bwm;
}
document.getElementById("tot").value = "RM " + tot;
}
<form id="theform" action="#">
<div>
<label for="place">Choose Destination :</label>
<select id="place" onChange="handleClick()">
<option value="swk">Sarawak</option>
<option value="sbh">Sabah</option>
<option value="wm">WestMalaysia</option>
</select>
</div>
<div>
<label for="kilo">Amount of KG :</label>
<input id="kilo" type="text">
</div>
<div>
<label>Total :</label>
<input id="tot" type="text" readonly="readonly">
</div>
<div>
<label></label>
<input id="calc" type="button" value="calculate">
<input id="r" type="reset" value="clear">
</div>
</form>
I Removed the left-hand side for assignment and set the value.
You defined the var for all instead of that you can use const.
Also form reset not required.
Here is solution of your code
<html>
<script type="text/javascript">
const bwm = 7.9;
const bswk = 14;
const bsbh = 15;
const wm = 2;
const swk = 11;
const sbh = 12;
let kilo, overkilo, f;
var tot;
function quote() {
const s = document.getElementById('place');
const place = s.options[s.selectedIndex].value;
const k = document.getElementById('kilo').value;
f = document.getElementById('theform');
// f.reset();
document.getElementById('calc').onclick = function() {
if (place == 'swk') {
tot = (k * swk) + bswk;
} else if (place == 'sbh') {
tot = (k * sbh) + bsbh;
} else {
tot = (k * wm) + bwm;
}
document.getElementById('tot').value = 'RM ' + parseFloat(tot);
}
}
</script>
<form id="theform" action="#">
<div>
<label for="place">Choose Destination :</label>
<select id="place" onChange="quote()">
<option value="swk">Sarawak</option>
<option value="sbh">Sabah</option>
<option value="wm">WestMalaysia</option>
</select>
</div>
<div>
<label for="kilo">Amount of KG :</label>
<input id="kilo" type="text">
</div>
<div>
<label>Total :</label>
<input id="tot" type="text" readonly="readonly">
</div>
<div>
<label></label>
<input id="calc" type="submit" value="calculate">
<input id="r" type="reset" value="clear">
</div>
</form>
</html>
I want to achieve an automatic clear and display another value corresponds to new inputted data
This is my html code for input data and text area
function getInputValue(){
var integer = document.getElementById("integer").value;
var text = document.getElementById("answer");
for (var i = 1; i <= integer; i++) {
if (i % 15 == 0){
text.append( i, "= ","fizzbuzz\n")
}
else if (i % 3 == 0){
text.append( i, "= ","fizz \n")
}
else if (i % 5 == 0){
text.append( i, "= ","buzz \n")
}
else{
text.append(i, "= \n")
}
}
}
<div class="form-floating mb-3">
<input class="form-control" id="integer" onChange="getInputValue()" type="text" placeholder="Input an Integer for N" data-sb-validations="required" />
<label for="integer">Input an Integer for N</label>
</div>
<div class="col-lg-6 form-floating answer mb-3">
<textarea disabled class="form-control" id="answer" type="text" placeholder="Answer" style="height: 20rem"></textarea>
</div>
If you will try to run the snippet you can see that if you will change the value in the input tag the textarea will just stack all the outputs
Because you are using append() always it is always adding to content. Just clear it everytime onChange is triggered so it resets. You can use :
text.innerHTML = '';
function getInputValue(){
var integer = document.getElementById("integer").value;
var text = document.getElementById("answer");
text.innerHTML = '';
for (var i = 1; i <= integer; i++) {
if (i % 15 == 0){
msg = i + "fizzbuzz";
text.append( i, "= ","fizzbuzz\n")
}
else if (i % 3 == 0){
text.append( i, "= ","fizz \n")
}
else if (i % 5 == 0){
text.append( i, "= ","buzz \n")
}
else{
text.append(i, "= \n")
}
}
}
<div class="form-floating mb-3">
<input class="form-control" id="integer" onChange="getInputValue()" type="text" placeholder="Input an Integer for N" data-sb-validations="required" />
<label for="integer">Input an Integer for N</label>
</div>
<div class="col-lg-6 form-floating answer mb-3">
<textarea disabled class="form-control" id="answer" type="text" placeholder="Answer" style="height: 20rem"></textarea>
</div>
Here is the solution:
let inputEl = document.querySelector('#integer')
let answerEl = document.querySelector('#answer')
inputEl.addEventListener('input', () => {
answerEl.value = ''
if (inputEl.value !== '') {
answerEl.value = getInputValue()
}
})
function getInputValue() {
var integer = inputEl.value;
var text = '';
for (var i = 1; i <= integer; i++) {
if (i % 15 == 0) {
text += i +"= fizzbuzz\n"
} else if (i % 3 == 0) {
text += i +" = fizz \n"
} else if (i % 5 == 0) {
text += i +" = buzz \n"
} else {
text += i +" = \n"
}
}
return text
}
<div class="form-floating mb-3">
<input class="form-control" id="integer" type="text" placeholder="Input an Integer for N" data-sb-validations="required" />
<label for="integer">Input an Integer for N</label>
</div>
<div class="col-lg-6 form-floating answer mb-3">
<textarea disabled class="form-control" id="answer" type="text" placeholder="Answer" style="height: 20rem"></textarea>
</div>
For context.
Remove the inline onChange="getInputValue()"
Setup getInputValue as a return type
Check if input is empty else run function
As far as I can see here, there isn't a way to clear a textarea without using an onclick function.
Try using the oninput event instead of the onchange event.
in my JavaScript
$("#inputDatabaseName").on("keyup", function(e) {
alert("Changed!");
console.info(this.value);
var nilaicli = this.value,
skorcli = document.getElementById("skorclis");
var cli1 = parseFloat(nilaicli.value) || 2;
var x = cli1.toFixed(2);
if (x <= 39.99 && x >= 0) {
skorcli.value = 1; //its the only come out and dont want change again if i input another number in inputid="inputDatabaseName". :(
} else if (x >= 40.0 && x <= 59.99) {
skorcli.value = 2;
} else if (x >= 60.0 && x <= 79.99) {
skorcli.value = 3;
} else if (x >= 80.0 && x <= 89.99) {
skorcli.value = 4;
} else if (x >= 90.0 && x <= 100) {
skorcli.value = 5;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-3">
<div class="card card-chart">
<div class="card-header">
<div class="row">
<p> Input CLI</p>
</div>
<div class="card-body">
<div class="row">
<div class="col-8">
<label>Nilai CLI : </label>
<input type="text" name="nama" class="col-sm-4 nilaicli" id="inputDatabaseName">
<br>
</div>
</div>
<div class="row">
<div class="col-8">
<label> Skor CLI : </label>
<input type="text" name="nama" class="col-sm-3" id="skorclis" readonly="true" onkeypress="return onlyNumberKey(event)">
</div>
</div>
</div>
</div>
</div>
</div>
i want change value in inputid="skorclis" again if i input something in inputid="inputDatabaseName".
but my script dont want change value at inputid="skorclis" repeatly. only want the first if statement. and dont want change again. how to make it become change again?
$("#inputDatabaseName").on("keyup", function(e) {
const nilaicli = this.value;
const cli1 = parseFloat(nilaicli) || 2;
const x = cli1.toFixed(2);
hanldeChange(x);
});
const hanldeChange = (x) => {
const skorcli = document.getElementById("skorclis");
console.info(x);
if (x <= 39.99) {
skorcli.value = 1;
} else if (x <= 59.99) {
skorcli.value = 2;
} else if (x <= 79.99) {
skorcli.value = 3;
} else if (x <= 89.99) {
skorcli.value = 4;
} else if (x <= 100) {
skorcli.value = 5;
}
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-3">
<div class="card card-chart">
<div class="card-header">
<div class="row">
<p> Input CLI</p>
</div>
<div class="card-body">
<div class="row">
<div class="col-8">
<label>Nilai CLI : </label>
<input type="text" name="nama" class="col-sm-4 nilaicli" id="inputDatabaseName">
<br>
</div>
</div>
<div class="row">
<div class="col-8">
<label> Skor CLI : </label>
<input type="text" name="nama" class="col-sm-3" id="skorclis" readonly="true" onkeypress="return onlyNumberKey(event)">
</div>
</div>
</div>
</div>
</div>
</div>
Have look to that:
const myForm = document.querySelector('#my-form') // use a form, it is
// usefull to access on myForm.nilaicli
// element or any one else
myForm.nilaicli.addEventListener('input',function() // use input event, it's also work with mouse copy/paste
{
let x = parseFloat(this.value) || 2
this.value = x // .toFixed(2)
switch (true)
{
case (x >= 0 && x < 40) : myForm.skorclis.value = 1; break;
case (x >= 40 && x < 60) : myForm.skorclis.value = 2; break;
case (x >= 60 && x < 80) : myForm.skorclis.value = 3; break;
case (x >= 80 && x < 90) : myForm.skorclis.value = 4; break;
case (x >= 90 && x <= 100) : myForm.skorclis.value = 5; break;
}
})
myForm.onsubmit = e => e.preventDefault() // disable form submit
fieldset {
display : block;
margin : 1em;
width : 17em;
}
label {
display : block;
margin : 1em;
}
label input {
float : right;
padding : 0 .7em;
width : 9em;
}
<form id="my-form">
<fieldset>
<legend>Input CLI</legend>
<label>
Nilai CLI :
<input type="text" name="nilaicli">
</label>
<label>
Skor CLI :
<input type="text" name="skorclis" readonly >
</label>
</fieldset>
</form>
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();
}
<pre>
<div class="quantity">
<input type="number" name="qty" id="qty" value="1" class="form-qty form-control" min="1">
<div class="quantity-nav">
<div class="quantity-button quantity-up qty-up">+</div>
<div class="quantity-button quantity-down qty-down">-</div>
</div>
</div>
<pre>
This is loop.
I want to get input value when i click quantity up & down button each time. There are multiple elements.
How to find input value in javascript by clicking button up & down.
You can add onClick event with parents feature to detect the inputs near to the button.
$(document).on('click','.quantity-up',function(){
$qtyElemnt = $(this).parents('.quantity').find('.form-qty');
$qty = $qtyElemnt.val();
$qtyElemnt.val(Number($qty)+1);
});
$(document).on('click','.quantity-down',function(){
$qtyElemnt = $(this).parents('.quantity').find('.form-qty');
$qty = $qtyElemnt.val();
$qtyElemnt.val(Number($qty)-1);
});
.quantity {
padding: 10px;
}
.quantity-nav{
display: inline-block;
}
.quantity-button {
display: inline-block;
padding: 5px;
background-color: #c7c5c5;
border: 1px solid #585353;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<div class="quantity">
<input type="number" name="qty" value="1" class="form-qty form-control" min="1">
<div class="quantity-nav">
<div class="quantity-button quantity-up qty-up">+</div>
<div class="quantity-button quantity-down qty-down">-</div>
</div>
</div>
<div class="quantity">
<input type="number" name="qty" value="1" class="form-qty form-control" min="1">
<div class="quantity-nav">
<div class="quantity-button quantity-up qty-up">+</div>
<div class="quantity-button quantity-down qty-down">-</div>
</div>
</div>
<div class="quantity">
<input type="number" name="qty" value="1" class="form-qty form-control" min="1">
<div class="quantity-nav">
<div class="quantity-button quantity-up qty-up">+</div>
<div class="quantity-button quantity-down qty-down">-</div>
</div>
</div>
</div>
Thanks :-)
Actually your problem is quite easy to solve.
Try to add this script at the end of your <body>.
I suggest you to make some modifications in your html too: use <button> or <input type="button"or even <a> tags for your controls.
I added some logic about the min/max/step attributes you can set on a <input type="number"> but this is optional. It's up to you to change this.
document.addEventListener("DOMContentLoaded", function() {
const qtyWraps = document.getElementsByClassName('quantity');
for (let i = 0; i < qtyWraps.length; i++) {
const qtyWrap = qtyWraps.item(i);
const input = qtyWrap.querySelector('.form-qty');
const up = qtyWrap.querySelector('.qty-up');
const down = qtyWrap.querySelector('.qty-down');
const output = qtyWrap.querySelector('.output');
up.addEventListener('click', function(e) {
e.preventDefault();
addValue(1);
});
down.addEventListener('click', function(e) {
e.preventDefault();
addValue(-1);
});
input.addEventListener('input', function() {
output.textContent = input.value
});
const addValue = function(value) {
const current = parseInt(input.value);
const min = input.getAttribute('min') || -Infinity;
const max = input.getAttribute('max') || Infinity;
const step = input.getAttribute('step') || 1;
const newValue = Math.min(max, Math.max(min, current + value * step));
input.value = newValue;
if (newValue <= min) down.setAttribute('disabled', 'disabled');
else down.removeAttribute('disabled');
if (newValue >= max) up.setAttribute('disabled', 'disabled');
else up.removeAttribute('disabled');
input.dispatchEvent(new Event('input'));
}
addValue(0)
}
});
.quantity {
display: block;
width: 500px;
margin: auto;
text-align: center;
}
.quantity .form-qty {
display: inline-block;
}
.quantity .quantity-nav {
display: inline-block;
}
.quantity .output {
background: yellow;
width: 500px;
margin: 1em auto 0;
}
<div class="quantity">
<input type="number" name="qty" id="qty" value="1" class="form-qty form-control" min="1">
<div class="quantity-nav">
<button class="quantity-button quantity-up qty-up">+</button>
<button class="quantity-button quantity-down qty-down">-</button>
</div>
<!-- I put it here to show the output result -->
<div class="output">1</div>
</div>
You can use localStorage to store the value of your quantity, this would make the data persistent.
Please check the below code snippet:
const down = document.querySelector('.down');
const up = document.querySelector('.up');
const input = document.querySelector('.quantity');
// store utility function
const store = {
existsIn: function(key) {
return this.getFromKey(key) !== null;
},
getFromKey: function(key) {
return window.localStorage.getItem(key);
},
add: function(key, value) {
const storeSource = window.localStorage.setItem(key, value);
}
}
const quantity = Object.create(store);
quantity.exists = function() {
return this.existsIn('quantity');
}
quantity.increase = function() {
let storedQuantity = this.exists() ? parseFloat(this.getFromKey('quantity')) : 0;
storedQuantity = storedQuantity + 1;
this.add('quantity', storedQuantity);
}
quantity.decrease = function() {
let storedQuantity = this.exists() ? parseFloat(this.getFromKey('quantity')) : 0;
if(storedQuantity > 0) {
storedQuantity = storedQuantity - 1;
}
this.add('quantity', storedQuantity);
}
quantity.show = function() {
return this.exists() ? this.getFromKey('quantity') : 0;
}
// event listeners for up and down buttons
up.addEventListener('click', function() {
quantity.increase();
// update input on button click
input.value = quantity.show();
})
down.addEventListener('click', function() {
quantity.decrease();
// update input on button click
input.value = quantity.show();
})
// update input on page load
input.value = quantity.show();
There you can find a working fiddle:
https://jsbin.com/tavalocoti/5/edit?html,js,console,output