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>
Related
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?
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>
Everything in this code functions how I want it to except I don't know how to make whatever number is on the slider be applied to the number variable. Any help you can give I would appreciate so much!
var range = document.querySelector('.inputRange');
var field = document.getElementById('num1');
range.addEventListener('input', function (e) {
field.value = e.target.value;
});
field.addEventListener('input', function (e) {
range.value = e.target.value;
});
var number = 2000;
document.getElementById("id").innerHTML = number.toLocaleString('en');
var number2 = number;
if (number2 >= 10000) {
number2 = Math.round(+number + 10);
}
else if (number2 >= 5000) {
number2 = Math.round(+number + 5);
}
else {
number2 = Math.round(+number + 1);
}
document.getElementById("id2").innerHTML = number2.toLocaleString('en');
<input class="inputRange" type="range" min="1000" max="50000" value="1000" step="1000" id="slider"/>
<input class="inputNumber" id="num1" min="0" max="100" type="number" value="1000" />
<p> <span id="id"></span></p>
<p>$<span id="id2"></span></p>
http://jsfiddle.net/rY3Tj/292/ This should help!
var range = document.querySelector('.inputRange');
var field = document.getElementById('num1');
var number2 = 2001;
var numberHtml = document.getElementById("id");
var number2Html = document.getElementById("id");
range.addEventListener('input', function (e) {
field.value = e.target.value;
SetNumberValues(field.value);
});
field.addEventListener('input', function (e) {
field.value = e.target.value;
SetNumberValues(field.value);
});
function SetNumberValues(fieldValue)
{
numberHtml.innerHTML = fieldValue.toLocaleString('en');
if (fieldValue >= 10000) {
number2 = Math.round(+fieldValue + 10);
}
else if (fieldValue >= 5000) {
number2 = Math.round(+fieldValue + 5);
}
else {
number2 = Math.round(+fieldValue + 1);
}
document.getElementById("id2").innerHTML = number2.toLocaleString('en');
}
<input class="inputRange" type="range" min="1000" max="50000" value="1000" step="1000" id="slider"/>
<input class="inputNumber" id="num1" min="1000" max="50000" step="1000" type="number" value="1000" />
<p> <span id="id">2000</span></p>
<p>$<span id="id2">2001</span></p>
Here is working code: http://jsfiddle.net/e0s8z4hm/
Basically in range.addEventListener you were not updating value in #id2.
Current :
range.addEventListener('input', function (e) {
field.value = e.target.value;
});
Do it :
range.addEventListener('input', function(e) {
field.value = e.target.value;
$('#id2').html(e.target.value); // add this line
});
This question already has answers here:
How to create an accurate timer in javascript?
(15 answers)
Closed 6 years ago.
I am building an activity timer, but the code I have is not working properly. The timer is going ~40% faster than real time. What's going wrong?
var sec = 00;
var min = 00;
var hr = 00;
var t;
var timer_is_on = 0;
function timedCount() {
if (min == 0) {
min = 1;
}
document.getElementById('seconds').value = sec;
document.getElementById('minutes').value = min;
$('.node-form .form-item:nth-child(4) input').val(min);
document.getElementById('hours').value = hr;
$('.node-form .form-item:nth-child(3) input').val(hr);
sec = sec + 1;
if (sec == 60) {
sec = 0;
min = min + 1;
if (min == 60) {
min = 1;
hr = hr + 1;
}
}
t = setTimeout("timedCount()", 1000);
}
function doTimer() {
if (!timer_is_on) {
timer_is_on = 1;
timedCount();
}
}
function stopCount() {
clearTimeout(t);
timer_is_on = 0;
}
function resetCount() {
stopCount();
sec = 0;
min = 0;
hr = 0;
document.getElementById('hours').value = 00;
$('.node-form .form-item:nth-child(3) input').val('0');
document.getElementById('minutes').value = 00;
$('.node-form .form-item:nth-child(4) input').val('0');
document.getElementById('seconds').value = 00;
}
function putInTimelog() {
// Put hours
var hourItems = [];
var hourFields = document.getElementById("node-form").getElementsByTagName("input");
for (var i = 0; i < hourFields.length; i++) {
//omitting undefined null check for brevity
if (hourFields[i].id.lastIndexOf("edit-field-timelog-hours-0-value-", 0) === 0) {
hourItems.push(hourFields[i]);
}
}
var hourField = 'edit-field-timelog-hours-0-value-';
hourField = hourField.concat(hourItems.length);
document.getElementById(hourField).value = hr;
// Put minutes
var minuteItems = [];
var hourFields = document.getElementById("node-form").getElementsByTagName("input");
for (var i = 0; i < hourFields.length; i++) {
//omitting undefined null check for brevity
if (hourFields[i].id.lastIndexOf("edit-field-timelog-minutes-0-value-", 0) === 0) {
minuteItems.push(hourFields[i]);
}
}
var minuteField = 'edit-field-timelog-minutes-0-value-';
minuteField = minuteField.concat(minuteItems.length);
alert(minuteField);
alert((minuteField).length);
document.getElementById(minuteField).value = min;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<span class="timer-title"><strong>Activity timer</strong></span>h:
<input id="hours" readonly="readonly" size="2" type="text" /> m:
<input id="minutes" readonly="readonly" size="2" type="text" /> s:
<input id="seconds" readonly="readonly" size="2" type="text" /><span class="timer-buttons"><input onclick="doTimer()" type="button" value="Start" /> <input onclick="stopCount()" type="button" value="Stop" /> <input onclick="resetCount()" type="button" value="Reset" /> </span>
</form>
View on JSFiddle
clock.js is my repo that might help when used in conjunction with window.setInterval(). Working example included.
Add <script src="https://rack.pub/clock.min.js"></script> to your HTML then call clock.now --> 1462248501241 each time you want a time snapshot. You can add and subtract intuitively from there.
The actual js looks like:
var clock = (function() {
// object to expose as public properties and methods such as clock.now
var pub = {};
//clock.now
Object.defineProperty(pub, "now", {
get: function () {
return Date.now();
}
});
//API
return pub;
}());
var doc = document;
var el = doc.getElementById('output');
window.setInterval(function(){
/// call your function here
el.innerHTML = clock.what.time(clock.now);
}, 500);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rack.pub/clock.min.js"></script>
<h2 id='output'></h2>
I'm writing a script where I need to get the total of two calculations and determine the total quote. The problem is I cannot get them to work when it comes to add them together. Bear in mind I'm a newbie and the code might no be fully optimized but I'm sure you will get the point. Any improvements on the code are more than welcome.
<div>
<fieldset>
<legend>Printing</legend>
Number of color pages:<input type="text" id="color" placeholder="Color Pages" onchange="printing();" onchange = "binding();" />
<input type="text" id="colorprice" readonly="readonly" /><br />
Number of black and white pages:<input type="text" id="black" placeholder="Black and White Pages" onchange="printing();" onchange = "binding();" />
<input type="text" id="blackprice" readonly="readyonly" /><br />
Total Pages:<input type="text" id="pages_total" readonly="readonly" /> <input type="text" id="sum_pages" readonly="readonly" onchange = "suming();"/>
</fieldset>
</div>
<div>
<fieldset>
<legend>Binding</legend>
Number of Hardbooks: <input type="text" id="books" placeholder="Number of Hardbooks" onchange="binding();" />
<input type="text" id="books_price" readonly="readonly" /><br />
Number of Softbacks: <input type="text" id="softback" placeholder="Number of Softbacks" onchange="binding();" />
<input type="text" id="soft_price" readonly="readonly" /><br />
Total Bindings: <input type="text" id="total_bindings" readonly="readonly" /><input type "text" id="total_price" readonly="readonly" />
</fieldset>
</div>
<p>Final quote:<input type="text" readonly="readonly" id="quote" /></p>
function printing() {
var blackPrice;
var colorPrice;
var printBlack = new Array(0.10, 0.08, 0.06, 0.05);
var printColor = new Array(0.40, 0.35, 0.30, 0.25);
var colorPages = parseInt(document.getElementById("color").value);
var blackPages = parseInt(document.getElementById("black").value);
if (colorPages < 11) {
colorPrice = colorPages * printColor[0];
}
else if (colorPages >= 11 && colorPages < 51){
colorPrice = colorPages * printColor[1];
}
else if (colorPages >= 51 && colorPages < 101){
colorPrice = colorPages * printColor[2];
}
else {
colorPrice = colorPages * printColor[3];
}
if (blackPages < 11) {
blackPrice = blackPages * printBlack[0];
}
else if (blackPages >= 11 && colorPages < 51){
blackPrice = blackPages * printBlack[1];
}
else if (blackPages >= 51 && colorPages < 101){
blackPrice = blackPages * printBlack[2];
}
else {
blackPrice = blackPages * printBlack[3];
}
var pagesTotal = colorPages + blackPages;
var printSum = blackPrice + colorPrice;
document.getElementById("colorprice").value = "$" + colorPrice.toFixed(2);
document.getElementById("blackprice").value = "$" + blackPrice.toFixed(2);
document.getElementById("sum_pages").value = "$" + printSum.toFixed(2);
document.getElementById("pages_total").value = pagesTotal;
return printSum;
}
function binding(){
var softbackPrice;
var hardbookPrice;
var hardBooks = new Array(37.50, 23.50);
var softBacks = new Array(3.75, 4.00, 4.25, 4.50, 4.75, 5.00, 5.25);
var noBooks = parseInt(document.getElementById("books").value);
var noSoftBacks = parseInt(document.getElementById("softback").value);
var colorPages = parseInt(document.getElementById("color").value);
var blackPages = parseInt(document.getElementById("black").value);
var totalPages = colorPages + blackPages;
if (noBooks == 1) {
hardbookPrice = hardBooks[0];
}
else {
hardbookPrice = (hardBooks[1] * (noBooks - 1)) + hardBooks[0];
}
if (totalPages <= 50) {
softbackPrice = softBacks[0] * noSoftBacks;
}
else if (totalPages > 50 && totalPages <= 100) {
softbackPrice = softBacks[1] * noSoftBacks;
}
else if (totalPages > 100 && totalPages <= 150) {
softbackPrice = softBacks[1] * noSoftBacks;
}
else if (totalPages > 150 && totalPages <=200) {
softbackPrice = softBacks[2] * noSoftBacks;
}
else if (totalPages > 200 && totalPages <= 250) {
softbackPrice = softBacks[3] * noSoftBacks;
}
else if (totalPages > 250 && totalPages <= 300) {
softbackPrice = softBacks[4] * noSoftBacks;
}
else if (totalPages > 300 && totalPages <= 350) {
softbackPrice = softBacks[5] * noSoftBacks;
}
else {
softbackPrice = softBacks[6] * noSoftBacks;
}
var totalPrice = softbackPrice + hardbookPrice;
var bindingsTotal = noSoftBacks + noBooks;
document.getElementById("books_price").value = "$" + hardbookPrice.toFixed(2);
document.getElementById("soft_price").value = "$" + softbackPrice.toFixed(2);
document.getElementById("total_bindings").value = bindingsTotal;
document.getElementById("total_price").value = "$" + totalPrice.toFixed(2);
return totalPrice;
}
function totalSum() {
var totalPrinting = printing();
var totalBinding = binding();
var subtotal = totalPrinting + totalBinding;
document.getElementIdBy("quote").value = subtotal;
}
Here is the working solution. http://jsfiddle.net/UHnRL/2/
= is missing for type in the below markup
<input type "text" id="total_price" readonly="readonly" />
It works for me (mostly): http://jsfiddle.net/UHnRL/
There is an issue with the first onchange calculation, because the other number of pages is NaN after you do the parseInt. You should default it to zero if the text box is blank.
You can use the isNaN[MDN] function to resolve the calculation issue:
var colorPages = parseInt(document.getElementById("color").value);
var blackPages = parseInt(document.getElementById("black").value);
if (isNaN(colorPages))
{
colorPages = 0;
}
if (isNaN(blackPages))
{
blackPages = 0;
}