How can I display all guessed numbers in this lottery function? - javascript

I've created some simple lottery function in JS. All works fine.
The only issue I'm facing is how to display all numbers which have been guessed?
I have 6 independent spaces where numbers must be provided and my goal is to display the rolled number from random space, it must be just provided in one of the 6 spaces. That works for me, but only 1 number displays.
I'm looking for solution how to display all the guessed numbers?
function losowanie1() {
var wybor = 6;
var dostepne = 6;
r = new Array(dostepne)
var xd0 = document.getElementById("pole1").value
var xd1 = document.getElementById("pole2").value
var xd2 = document.getElementById("pole3").value
var xd3 = document.getElementById("pole4").value
var xd4 = document.getElementById("pole5").value
var xd5 = document.getElementById("pole6").value
y = new Array(6)
y[0] = xd0
y[1] = xd1
y[2] = xd2
y[3] = xd3
y[4] = xd4
y[5] = xd5
z = new Array(6)
for (var i = 0; i <= dostepne - 1; i++) {
r[i] = Math.floor((Math.random() * (49 - 1)) + 1);
if ((y[i] == r[0]) || (y[i] == r[1]) || (y[i] == r[2]) || (y[i] == r[3]) || (y[i] == r[4])) {
document.getElementById("zatw").innerHTML = y[i]
}
}
document.getElementById("wysw").innerHTML = r;
}
<div id="wysw"></div>
<div id="dupa">
<input type="text" id="pole1" /><input type="text" id="pole2" /><input type="text" id="pole3" /><input type="text" id="pole4" /><input type="text" id="pole5" /><input type="text" id="pole6" />
<br></br>
<input type="reset" id="tak" value="zatwierdz" onclick="losowanie1();" />
<br></br>
<div id="zatw"></div>

What the below still misses is to make sure the user don't repeats numbers in the inputs.
I won't do that since I would neither use inputs for that purpose, but rather predefined checkboxes (yes, 38 checkboxes) and make sure , on submit, exactly 6 are checked.
Anyways, hope this might be helpful:
function lottoGenerate(min, max) {
// Shuffle: https://stackoverflow.com/a/6274381/383904
const a = Array.from({length: max}, (_, v) => v + 1);
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a.slice(0, min);
}
function play() {
const guessed_nums = [];
const lotto_nums = lottoGenerate(6, 38); // Generate 6 random unique lotto numbers
const player_nums = Array.from(document.querySelectorAll('.num')).map(el => {
const n = parseInt(el.value, 10);
const isGuessed = lotto_nums.includes(n);
if (isGuessed) {
guessed_nums.push(n); // Insert the guessed number!
el.style.background = 'lightgreen';
} else {
el.style.background = 'red'
}
return n
});
document.getElementById('gen').textContent = lotto_nums.join(', ');
document.getElementById('player').textContent = player_nums.join(', ');
document.getElementById('response').innerHTML = `
You guessed ${guessed_nums.length} numbers!<br>
The numbers are: ${guessed_nums.join(', ')}
`;
}
document.getElementById('play').addEventListener('click', play);
<input class="num" type="number" min=1 max=38 value="1">
<input class="num" type="number" min=1 max=38 value="2"><br>
<input class="num" type="number" min=1 max=38 value="3">
<input class="num" type="number" min=1 max=38 value="4"><br>
<input class="num" type="number" min=1 max=38 value="5">
<input class="num" type="number" min=1 max=38 value="26"><br>
<button id="play">PLAY LOTTO 6/38</button>
<div>Numbers: <span id="gen"></span></div>
<div>User played: <span id="player"></span></div>
<div id="response"></div>

Related

The calculation result always a 'NaN'

let z = document.getElementById('id_z')
let x = document.getElementById('id_x')
let y = document.getElementById('id_y')
$("#id_a, #id_b, #id_c, #id_d, #id_e").keyup(function () {
let a = $('#id_a').val()
let b = $('#id_b').val()
let c = $('#id_c').val()
let d = $('#id_d').val()
let e = $('#id_e').val()
z.value = ((c * 3.175) / a).toFixed(0)
x.value = (b*e)+(d*(e - 1))+15
// y variable throws the error
y.value = ((c*3.175) - (a * z))/z
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>Value A:</label>
<input type="number" class="numberinput form-control" required="" id="id_a">
<label>Value B:</label>
<input type="number" class="numberinput form-control" required="" id="id_b">
<label>Value C:</label>
<input type="number" class="numberinput form-control" required="" id="id_c">
<label>Value D:</label>
<input type="number" class="numberinput form-control" required="" id="id_d">
<label>Value E:</label>
<input type="number" class="numberinput form-control" required="" id="id_e">
<div>
<label>Value Z:</label>
<input type="number" class="numberinput form-control" required="" id="id_z">
<label>Value x:</label>
<input type="number" class="numberinput form-control" required="" id="id_x">
<label>Value Y:</label>
<input type="number" class="numberinput form-control" required="" id="id_y">
</div>
I am creating a calculation process using JavaScript based on what the user input and delivering the result. When I try to put a number in "gear", it shows the error in the console "specified value cannot be parsed or is out of range".
const z = document.getElementById('id_z')
const x = document.getElementById('id_x')
const y = document.getElementById('id_y')
$("#id_c, #id_d, #id_e, #id_a, #id_b").keyup(function () {
const a = $('#id_a').val()
const b = $('#id_b').val()
const c = $('#id_c').val()
const d = $('#id_d').val()
const e = $('#id_e').val()
z.value = ((c * 3.175) / a).toFixed(0)
x.value = (a*e)+(d*(e - 1)+15)
// y variable throws the error
y = ((c*3.175) - (a * z))/z
console.log(y)
console.log(typeof(y))
});
For z and x looks fine but the calculation result for X always throws NaN. I need some advice on this problem, Thank you.
a) .val() provides value in string format so you have to convert it into numbers. So use parseFloat.
b) Instead of using constant use var or let as the constant value cannot be changed each time the different input values change.
c) As x,y,z are DOM elements so you can not use them directly in your calculation. You need to change your code like below.
Working snippet:
var z = document.getElementById('id_z')
var x = document.getElementById('id_x')
var y = document.getElementById('id_y')
$("#id_c, #id_d, #id_e, #id_a, #id_b").keyup(function() {
var a = parseFloat($('#id_a').val()) || 0;
var b = parseFloat($('#id_b').val()) || 0;
var c = parseFloat($('#id_c').val()) || 0;
var d = parseFloat($('#id_d').val()) || 0;
var e = parseFloat($('#id_e').val()) || 0;
var first = ((c * 3.175) / a).toFixed(0);
var second = (a * e) + (d * (e - 1) + 15);
var third = ((c * 3.175) - (a * first)) / first;
z.value = first;
x.value = second;
y.value = !isNaN(third) ? third : 0;
});
input[type="text"]
{
width:90%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<br>
id_a<input type="text" id="id_a">
<br> id_b
<input type="text" id="id_b">
<br> id_c
<input type="text" id="id_c">
<br> id_d
<input type="text" id="id_d">
<br> id_e
<input type="text" id="id_e">
<br> id_x
<input type="text" id="id_x">
<br> id_y
<input type="text" id="id_y">
<br> id_z
<input type="text" id="id_z">
<br>
const z = document.getElementById('id_z')
const x = document.getElementById('id_x')
const y = document.getElementById('id_y')
$("#id_c, #id_d, #id_e, #id_a, #id_b").keyup(function () {
const a = $('#id_a').val()
const b = $('#id_b').val()
const c = $('#id_c').val()
const d = $('#id_d').val()
const e = $('#id_e').val()
z.value = ((c * 3.175) / a).toFixed(0)
// Add error handling to calculation for 'x'
if (!isNaN(a) && !isNaN(e) && !isNaN(d)) {
x.value = (a * e) + (d * (e - 1) + 15)
} else {
x.value = ''
}
// Add error handling to calculation for 'y'
if (!isNaN(c) && !isNaN(a) && !isNaN(z)) {
y.value = ((c * 3.175) - (a * z)) / z
} else {
y.value = ''
}
console.log(y.value)
console.log(typeof(y.value))
});
Just do parseFloat() in javascript to prevent this.
Below is the code for your problem:
let a = parseFloat($('#id_a').val());
let b = parseFloat($('#id_b').val());
let c = parseFloat($('#id_c').val());
let d = parseFloat($('#id_d').val());
let e = parseFloat($('#id_e').val());
Hope this work for you.

How do I use an input to define decimals for other inputs?

I am trying to set the number of decimals of many inputs by using a specific input.
Here is what I am doing:
window.oninput = function(event) {
var campo = event.target.id;
// DECIMALS
if (campo == "decimalTemp") {
var i = decimalTemp.value;
ºC.value.toFixed = i;
ºK.value.toFixed = i;
ºF.value.toFixed = i;
ºRa.value.toFixed = i;
}
// TEMPERATURE
if (campo == "ºC") {
ºK.value = (ºC.value * 1 + 273.15).toFixed(i);
ºF.value = (ºC.value * 1.8 + 32).toFixed(i);
ºRa.value = ((ºC.value * 1 + 273.15) * 1.8).toFixed(i);
} else if (campo == "ºK") {
ºC.value = (ºK.value * 1 - 273.15).toFixed(2);
ºF.value = (ºK.value * 1.8 - 459.889).toFixed(2);
ºRa.value = (ºK.value * 1.8).toFixed(2);
} else if (campo == "ºF") {
ºC.value = ((ºF.value * 1 - 32) / 1.8).toFixed(2);
ºK.value = ((ºF.value * 1 + 459.67) / 1.8).toFixed(2);
ºRa.value = (ºF.value * 1 + 459.67).toFixed(2);
} else if (campo == "ºRa") {
ºC.value = (ºRa.value / 1.8 - 273.15).toFixed(2);
ºK.value = (ºRa.value / 1.8).toFixed(2);
ºF.value = (ºRa.value * 1 - 459.67).toFixed(2);
}
};
<h3>Temperature <input type="number" min="0" max="12" value="0" id="decimalTemp" name="decimal" placeholder="Decimal"> <small>Decimals<small></h3>
Celsius (ºC) <input id="ºC" type="number" min="-273.15" value="20">
<br> Kelvin (K) <input id="ºK" type="number" min="0" value="293">
<br> Farenheit (ºF) <input id="ºF" type="number" min="-459.67" value="68">
<br> Rankine (ºRa) <input id="ºRa" type="number" min="0" value="528">
In summary, I would like to know if this construction is correct:
var i = decimalTemp.value;
ºC.value.toFixed = i;
I already tried something like:
ºC.value.toFixed(i);
But didn't work. Any idea where am I wrong?

JavaScript array application

I'm trying to create a sample accounting system, the checkbox can be add to the total after it's checked and the input text is the amount of the money.
but my result keep getting zero, I can't figure it out.
Anyone can help me handle this problem?
I've test that the length of total_ary is 0, I think that is the mainly problem
function Totalamount() {
var input_cb = document.getElementsByName('cb');
var amount = [];
var total_ary = [];
var total = 0;
var price = [10, 20, 30];
var i = 0;
for (i = 0; i < input_cb.length; i++) {
if (input_cb[i].checked) {
amount.push(document.getElementsByName("amount").value); //get amounts of the products
} else {
amount.push(0); //If there is no input, add 0 to the array
}
}
for (i = 0; i < total_ary.length; i++) {
total_ary.push(parseInt(amount[i] * price[i])); // Add the products' total price to array
total += parseInt(total_ary[i]); //Counting the total money
}
document.getElementById("result").innerHTML = "$" + 0;
document.getElementById("result").innerHTML = "$" + total ;
}
<fieldset>
<input type="checkbox" name="cb" checked>$10:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$20:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$30:<input type="text" name="amount"><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">
You do
document.getElementsByName("amount").value
but getElementsByName returns a collection, not an element.
You do
var total_ary = [];
// ... code that doesn't reference total_ary
for (i = 0; i < total_ary.length; i++) {
total_ary.push(parseInt(amount[i] * price[i])); // Add the products' total price to array
total += parseInt(total_ary[i]); //Counting the total money
}
But since the code in between doesn't reference total_ary, the total ends up being 0.
From a selected checkbox, you need to navigate to the associated input:
document.getElementsByName("amount")[i].value
since i is the cb index you're iterating over, the same i in the amount collection will refer to the input you need.
Or, more elegantly, just navigate to the next element in the DOM when a checkbox is checked, and take the number for each product's price from the DOM too. You can also select only the checked checkboxes immediately with a :checked selector, and attach the event listener using addEventListener (instead of an inline handler; inline handlers should be avoided)
document.querySelector('button').addEventListener('click', () => {
let total = 0;
for (const input of document.querySelectorAll('[name=cb]:checked')) {
const price = input.nextSibling.textContent.match(/\d+/)[0];
const amount = input.nextElementSibling.value;
total += price * amount;
}
document.getElementById("result").innerHTML = total + "元";
});
<fieldset>
<input type="checkbox" name="cb" checked>$10:<input><br>
<input type="checkbox" name="cb" checked>$20:<input><br>
<input type="checkbox" name="cb" checked>$30:<input><br>
</fieldset>
<button>Count</button>
<p>Total = <span id="result">
document.getElementsByName() returns a collection of elements. so calling value property will not work there as it does not have such property.
You can hold input elements with amount_inputs variable and iterate over it (in the example below by using spread syntax and Array.reduce())
And with Array.reduce() you can calculate the sum of the prices. There is no need for var amount = [] and var total_ary = [] variables.
Hope this helps
function Totalamount() {
var input_cb = document.getElementsByName('cb');
var amount_inputs = document.getElementsByName("amount")
var total = 0;
var price = [10, 20, 30];
total = [...input_cb].reduce((total, cb, i) => {
if(cb.checked){
total += (parseInt(amount_inputs[i].value) || 0) * price[i]
// ^^^^^^^^^ This is to avoid NaN multiplication
}
return total
},0);
document.getElementById("result").innerHTML = "$" + 0;
document.getElementById("result").innerHTML = total + "元";
}
<fieldset>
<input type="checkbox" name="cb" checked>$10:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$20:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$30:<input type="text" name="amount"><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">
Use Index while retrieving the element from document.getElementsByName("amount");
Use for loop on amount array not on total_ary
function Totalamount() {
var input_cb = document.getElementsByName('cb');
var amount = [];
var total_ary = [];
var total = 0;
var price = [10, 20, 30];
var i = 0;
for (i = 0; i < input_cb.length; i++) {
if (input_cb[i].checked) {
amount.push(document.getElementsByName("amount")[i].value); //get amounts of the products
} else {
amount.push(0); //If there is no input, add 0 to the array
}
}
for (i = 0; i < amount.length; i++) {
total_ary.push(parseInt(amount[i] * price[i])); // Add the products' total price to array
total += isNaN(parseInt(total_ary[i])) ? 0 : parseInt(total_ary[i]); //Counting the total money
}
document.getElementById("result").innerHTML = "$" + 0;
document.getElementById("result").innerHTML = "$" + total ;
}
<fieldset>
<input type="checkbox" name="cb" checked>$10:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$20:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$30:<input type="text" name="amount"><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">
You have made a few mistakes:
(1) If you want to keep all the checkboxes checked at initial stage
use checked="true" in place of checked
(2) getElementsByName("amount") returns an array, so you should use the index as well
(3) total_ary length is 0 initially.. therefore, you should run the loop with input_cb. (Here, you can do both the task with a single loop: refer code below)
Refer the code with corrections:
<!DOCTYPE html>
<html>
<head>Order sys
<script>
function Totalamount() {
var input_cb = document.getElementsByName('cb');
var amount = [];
var total = 0;
var price = [10,20,30];
var i=0;
for (i = 0; i < input_cb.length; i++) {
if (input_cb[i].checked){
amount.push(parseInt(document.getElementsByName("amount")[i].value)); //get amounts of the products
}
else{
amount.push(0); //If there is no input, add 0 to the array
}
total += parseInt(amount[i] * price[i]) //Counting the total money
}
document.getElementById("result").innerHTML = "$" + 0;
document.getElementById("result").innerHTML = total + "元";
}
</script>
</head>
<body>
<fieldset>
<input type = "checkbox" name="cb" checked="true">$10:<input type="text" id="amount_milk" name="amount" ><br>
<input type = "checkbox" name="cb" checked="true">$20:<input type="text" id="amount_soymlik" name="amount"><br>
<input type = "checkbox" name="cb" checked="true">$30:<input type="text" id="amount_blacktea" name="amount" ><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">
</body>
</html>
You can refactor your code:
Fist use inputs of type number <input type="number" name="amount"> to accept only numbers from your end users
Then, you can work with indexed arrays like [...document.querySelectorAll('input[name="cb"]')] and loop only one time with Array.prototype.reduce() to get the total
Code example:
function Totalamount() {
const inputNumberArr = [...document.querySelectorAll('input[name="cb"]')]
const inputAmountArr = [...document.querySelectorAll('input[name="amount"]')]
const priceArr = [10, 20, 30]
const total = inputNumberArr.reduce((a, c, i) => {
const num = c.checked ? +inputAmountArr[i].value : 0
return a + num * priceArr[i]
}, 0)
document.getElementById('result').innerHTML = '$' + 0
document.getElementById('result').innerHTML = '$' + total
}
<fieldset>
<input type="checkbox" name="cb" checked> $10:
<input type="number" name="amount"><br>
<input type="checkbox" name="cb" checked> $20:
<input type="number" name="amount"><br>
<input type="checkbox" name="cb" checked> $30:
<input type="number" name="amount"><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">
Is this what you are looking for?
Errors that I identified.
Making use of document.getElementsByName("amount").value instead of making the respective amount field you were making use of the global selector.
Trying to loop total_ary array instead of amount array.
function Totalamount() {
var input_cb = document.getElementsByName('cb');
var amountInput = document.getElementsByName('amount');
var amount = [];
var total_ary = [];
var total = 0;
var price = [10,20,30];
var i=0;
for (i = 0; i < input_cb.length; i++) {
if (input_cb[i].checked && amountInput[i].value){
amount.push(parseInt(amountInput[i].value)); //get amounts of the products
}
else{
amount.push(0); //If there is no input, add 0 to the array
}
}
for (i = 0; i < amount.length; i++) {
total_ary.push(parseInt(amount[i] * price[i])); // Add the products' total price to array
total += parseInt(total_ary[i]); //Counting the total money
}
document.getElementById("result").innerHTML = "$" + 0;
document.getElementById("result").innerHTML = total + "元";
}
<fieldset>
<input type = "checkbox" name="cb" checked>$10
<input type="text" id="amount_milk" name="amount" ><br>
<input type = "checkbox" name="cb" checked>$20
<input type="text" id="amount_soymlik" name="amount"><br>
<input type = "checkbox" name="cb" checked>$30
<input type="text" id="amount_blacktea" name="amount" ><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">

Create three input box and named it as Min,Max and Mul respectively with one Button named it as "Validate". using Javascript

Requirement 1: Create three input boxes and named it as Min,Max and Mul respectively.
Requirement 2: Create a button and named it as "Validate".
Requirement 3: Following conditions on the input box should get satisfied.
1) Min<Max
2) Mul<Max
3) Mul<=Min
4) Min and Mul should be the factor of Max.
For eg : We have three inputs
Min Max Mul
5 10 5
Requirement 4: If any conditions get false, then that box should be highlighted by making the border of that box as "red".
For eg : We have three inputs:
Min Max Mul
5 10 6
Try this:
const min = document.getElementById('min')
const max = document.getElementById('max')
const mul = document.getElementById('mul')
const validate = () => {
const minValue = Number(min.value)
const maxValue = Number(max.value)
const mulValue = Number(mul.value)
if (minValue < maxValue &&
maxValue % minValue === 0) min.classList.remove('invalid')
else min.classList.add('invalid')
if (mulValue < maxValue &&
mulValue <= minValue &&
maxValue % minValue === 0) mul.classList.remove('invalid')
else mul.classList.add('invaid')
}
input.invalid {
border: 2px solid red;
}
<label for="min">Min</label>
<input type="number" id="min" name="min">
<br>
<label for="max">Max</label>
<input type="number" id="max" name="max">
<br>
<label for="mul">Mul</label>
<input type="number" id="mul" name="mul">
<br>
<button onclick="validate()">Validate</button>
Note: This will not work in IE.
function myFunction() {
var min=document.getElementById("demo1").value;
var max=document.getElementById("demo2").value;
var mul=document.getElementById("demo3").value;
min = parseInt(min);
max = parseInt(max);
mul = parseInt(mul);
if(!(min < max)){
document.getElementById('demo1').style.borderColor = "red";
}else{
document.getElementById('demo1').style.borderColor = "";
}
if(!(max > mul)){
document.getElementById('demo2').style.borderColor = "red";
} else{
document.getElementById('demo2').style.borderColor = "";
}
if(!(mul<= min)){
document.getElementById('demo3').style.borderColor = "red";
} else{
document.getElementById('demo3').style.borderColor = "";
}
if(!(max%min==0)){
document.getElementById('demo1').style.borderColor = "red";
} else{
document.getElementById('demo1').style.borderColor = "";
}
if(!(max%mul==0)){
document.getElementById('demo3').style.borderColor = "red";
} else{
document.getElementById('demo3').style.borderColor = "";
}
}
<html>
<body>
Min:<input type="text" name="a" id="demo1"><br>
Max:<input type="text" name="b" id="demo2"><br>
Mul:<input type="text" name="c" id="demo3"><br>
<button onclick="myFunction()"> Validate</button><br>
</body>
</html>

Summing up input values inside a forEach function

I'm trying to add up range input values but for reasons I don't know it starts from 0 when I change the next inputs value. Could it be that I'm calling the function inside a forEach function? Any help would be appreciated.
<input class="time-range" type="range" min="0" max="1440" value="0" step="15">
<input class="time-range" type="range" min="0" max="1440" value="0" step="15">
<input class="time-range" type="range" min="0" max="1440" value="0" step="15">
var d=document,
range = d.querySelectorAll(".time-range"),
time_total_hrs = d.querySelectorAll(".time_total .hours"),
time_total_min = d.querySelectorAll(".time_total .minutes"),
timeMax = 1440,
timeInput = 0,
timeLeft,num,hours,rhours,minutes,rminutes,current;
function getCurrent(){
if (defined(slide)){
return current = d.querySelector(".slide.active");
}
}
getCurrent()
function timeConvert(num) {
hours = (num / 60);
rhours = Math.floor(hours);
minutes = (hours - rhours) * 60;
rminutes = Math.round(minutes);
return num + " min = " + rhours + " h and " + rminutes + " min.";
}
function updateTotalTime(){
var tot = 0;
for (i = 0; i < range.length; i++){
tot = tot + parseInt(range[i].value, 10);
}
console.log("total time is: "+tot+"");
return tot;
}
function updateTimeLeft(){
timeLeft = parseInt(timeMax) - parseInt(updateTotalTime());
timeConvert(timeLeft);
console.log("time left:"+timeLeft+"")
for (i = 0; i < time_total_hrs.length; i++){
time_total_hrs[i].innerHTML = rhours;
time_total_min[i].innerHTML = rminutes;
}
}
function updateTimeSelected(){
timeConvert(timeInput);
current.querySelector(".time_current .hours").innerHTML = rhours;
current.querySelector(".time_current .minutes").innerHTML = rminutes;
}
function setWarning(){
for (i = 0; i < time_total.length; i++){
time_total[i].classList.add("warning");
}
}
function removeWarning(){
for (i = 0; i < time_total.length; i++){
time_total[i].classList.remove("warning");
}
}
[].forEach.call(range, function(el, i, els) {
el.addEventListener('input', function() {
timeInput = this.value;
updateTotalTime();
updateTimeLeft();
updateTimeSelected();
[].forEach.call(els, function(el) {
if (el !== this) {
el.setAttribute("max", timeLeft);
if (timeLeft === 0){
el.style.opacity = "0.5";
el.setAttribute("disabled", "true");
setWarning()
} else if (timeLeft > 0){
el.removeAttribute("disabled");
removeWarning()
} else {
}
} else {
}
}, this);
});
});
It's tricky to work out what you're trying to do and what's not working for you. I wonder if it's better to stop thinking in terms of "looping over everything" and start thinking along the lines of "I have some ranges, let's add the values together.
var ranges = Array.prototype.slice.call(document.querySelectorAll(".time-range"));
// ...
var total = ranges.reduce(function (subTotal, input) {
return subTotal + parseInt(input.value, 10);
}, 0);
You'd then have the total number of minutes and you can do whatever you like with that.
var ranges = Array.prototype.slice.call(document.querySelectorAll(".time-range"));
var hoursElement = document.querySelector(".time_total .hours");
var minutesElement = document.querySelector(".time_total .minutes");
function minsToHoursMins(raw) {
var hours = Math.floor(raw / 60);
var minutes = raw - (hours * 60);
return [hours, minutes];
}
document.querySelector(".time-range-holder").addEventListener("input", function () {
var total = ranges.reduce(function (subTotal, input) {
return subTotal + parseInt(input.value, 10);
}, 0);
var timeParts = minsToHoursMins(total);
hoursElement.innerHTML = timeParts[0];
minutesElement.innerHTML = timeParts[1];
});
<div class="time-range-holder">
<input class="time-range" type="range" min="0" max="1440" value="0" step="15">
<input class="time-range" type="range" min="0" max="1440" value="0" step="15">
<input class="time-range" type="range" min="0" max="1440" value="0" step="15">
</div>
<div class="time_total">
<p>Hours: <span class="hours"></span></p>
<p>Minutes: <span class="minutes"></span></p>
</div>
let inputs = [...document.querySelectorAll('input')]
let button = document.querySelector('button')
const SUM = () => inputs.reduce((prev, { value }) => +prev + +value, 0)
button.addEventListener('click', () => console.log(SUM()))
<input value="1"/>
<input value="1"/>
<input value="1"/>
<button>SUM</button>

Categories

Resources