Display Leading Zeros On Input Number Fields - javascript

I have two input fields representing hours and minutes.
<input type="number" min="0" max="24" step="1" value="00" class="hours">
<input type="number" min="0" max="0.60" step="0.01" value="00" class="minutes">
Which display as:
0:0
Or:
5:3
Is there a way to display it as:
00:00
Or:
05:03
i.e in 24-hour data format (before people suggest it, I can't use type="time").

You can add an onchange attribute to your input tag, which calls a javascript function.
<script>
function myFunction() {
var minuteValue = document.getElementById("minutes").value;
if (minuteValue.length < 2) {
minuteValue = "0" + minuteValue;
}
alert(minuteValue);
}
</script>
<input id="minutes" onchange="myFunction()"/>

function formatNums(num){
if (nums < 10){
return "0" + num;
}
}
var formattedHours = formatNums(hours);
var formattedMinutes = formatNums(minutes);
NOTE: This method uses type="text" so be sure to convert back to a number if needed. Number(formattedHours);

Add a leading zero with a JavaScript function.
const hours = document.getElementById("hours");
const minutes = document.getElementById("minutes");
function addLeadingZero(value) {
return value.length < 2 ? "0" + value : value;
}
hours.addEventListener("input", function() {
hours.value = addLeadingZero(hours.value);
});
minutes.addEventListener("input", function() {
minutes.value = addLeadingZero(minutes.value);
});
<input type="number" min="0" max="24" value="00" id="hours" class="hours">
<input type="number" min="0" max="59" value="00" id="minutes" class="minutes">

simple is the best
`${number}`.padStart(2, '0')

Related

how to implement multiple countdowns on the same DOM element

I have a DOM element, that contains values (milliseconds) from my database, and I want to implement a countdown for the values. For example, I can have 4 product deals in a section, with different duration in milliseconds, and i want to dynamically create different countdowns(HH:mm:ss) for each deal according to its duration.
Currently, the duration values (milliseconds) are stored in a hidden input field for each deal in the section.
<input type="hidden" name="" id='duration' value="{{this.deals.duration}}">
What i tried (it works fine for only one product deal). I used moment.js for the duration. and also for the countdown here:
<script type="text/javascript">
$(document).ready(function(){
console.log($('#duration').val());
var interval = 1000;
var durations = $('#duration').val();
setInterval(function(){
durations = moment.duration(durations - interval, 'milliseconds');
// console.log(durations);
$('#countdown').text(durations.hours() + ":" + durations.minutes() + ":" + durations.seconds())
}, interval);
})
</script>
Thanks very much :)
To add another answer to this question...
No dependencies (jQuery,Moment.js) and only for 24 hour duration (days,months,years are not calculated).
function countDown(elClass) {
let labels = document.querySelectorAll(elClass);
let now = Date.now();
labels.forEach((label,key) => {
let duration = document.getElementById(label.getAttribute('for')).value;
if(duration <= 86400000) {
let futureDate = now + parseInt(duration);
let counterInterval = setInterval(() => {
let diff = futureDate - Date.now();
if(diff <= 0) {
clearInterval(counterInterval);
return;
}
if(diff > 0) {
let milliseconds = diff%1000;
let seconds = parseInt(diff/1000)%60;
let minutes = parseInt(diff/(60*1000))%60;
let hours = parseInt(diff/(60*60*1000))%24;
label.innerHTML = hours.toString().padStart(2, '0')+':'+minutes.toString().padStart(2, '0')+':'+seconds.toString().padStart(2, '0')+'<br>';
}
},1000);
}
});
}
countDown('.countdown');
<input type="hidden" name="a" id="a" class='duration' value="5000"><label for="a" class="countdown"></label>
<input type="hidden" name="b" id="b" class='duration' value="15000"><label for="b" class="countdown"></label>
<input type="hidden" name="c" id="c" class='duration' value="190000"><label for="c" class="countdown"></label>
<input type="hidden" name="d" id="d" class='duration' value="2003200"><label for="d" class="countdown"></label>
<input type="hidden" name="e" id="e" class='duration' value="20067100"><label for="e" class="countdown"></label>
<input type="hidden" name="f" id="f" class='duration' value="86023104"><label for="f" class="countdown"></label>
$(document).ready(function(){
var interval = 1000;
setInterval(function(){
$('.duration').each(function () {
var t = Number($(this).val()) - interval;
if (t>=0) {
var d = moment.duration(t, 'milliseconds');
$(this).next('.countdown').text([
String(d.hours()).padStart(2,'0'),
String(d.minutes()).padStart(2,'0'),
String(d.seconds()).padStart(2,'0')
].join(':'));
$(this).val(t);
}
});
}, interval);
})
input + span {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js"></script>
<input type="hidden" name="a" class='duration' value="5000"><span class="countdown"></span>
<input type="hidden" name="b" class='duration' value="15000"><span class="countdown"></span>
<input type="hidden" name="c" class='duration' value="20000"><span class="countdown"></span>

Calculate the values of input where each input has different prices. Any shorter code for this?(javascript only)

The code below is working fine but what if there are 100 inputs? any shorter way to do this?
function checkTotal() {
var a = document.getElementById("sandwich").value;
var b = document.getElementById("burger").value;
var c = document.getElementById("cake").value;
var d = document.getElementById("coffee").value;
document.getElementById("total").value = parseInt(a) * 10 + parseInt(b) * 5 + parseInt(c) * 15 + parseInt(d) * 20;
}
<form role="form" name="listForm">
<label>Sandwich</label>
<input type="number" id="sandwich" value="0" onkeyup="checkTotal()"><br>
<label>Burger</label>
<input type="number" id="burger" value="0" onkeyup="checkTotal()"><br>
<label>Cake</label>
<input type="number" id="cake" value="0" onkeyup="checkTotal()"><br>
<label>Coffee</label>
<input type="number" id="coffee" value="0" onkeyup="checkTotal()"><br> Total: <input type="text" size="2" name="total" id="total" value="0" />
</form>
1) Here each input article has a different price.
2) The value of the input should be mutiply with its price given(Eg. if the sandwich has a price:30, and user inputs value 2 it should calculte the total=price*input value.)
3) i have my code which is working fine but is the above code is the right way to do?
4) what if there are 100 of article inputs. is there shorter code or should i create variable for each one?
what if there are 100 of article inputs. is there shorter code or
should i create variable for each one?
You can maintain a map
var idPriceMap = {
"sandwich" : 20,
"burger" : 10,
"cake" : 5,
"coffee" : 10
};
You can iterate this and produce your value using reduce
var output = Object.keys( idPriceMap ).reduce( function(a,b){
var value = +document.getElementById( b ).value;
a += value * idPriceMap[ b ];
return a;
}, 0);
document.getElementById( "total" ).value = output;
Another way to try is to give your elements a class and some data attributes that can be retrieved by JavaScript using dataset. You can then use them to make your calculations. That way you get rid of ids and you just have to change the HTML code to add a new element.
function checkTotal() {
var total = 0,
foods = document.querySelectorAll('.food');
for (var i = 0; i < foods.length; i++) {
var food = foods[i],
name = food.dataset.item,
price = parseInt(food.dataset.price),
howMany = parseInt(food.value);
console.log(howMany, name, 'costs', (howMany * price));
total += howMany * price;
}
document.getElementById('total').value = total;
}
<form role="form" name="listForm">
<label>Sandwich</label>
<input class="food" data-item="sandwich" data-price="30" type="number" value="0" onBlur="checkTotal()"><br>
<label>Burger</label>
<input class="food" data-item="burger" data-price="10" type="number" value="0" onBlur="checkTotal()"><br>
<label>Cake</label>
<input class="food" data-item="cake" data-price="5" type="number" value="0" onBlur="checkTotal()"><br>
<label>Coffee</label>
<input class="food" data-item="coffee" data-price="15" type="number" value="0" onBlur="checkTotal()"><br>
Total: <input type="text" size="2" name="total" id="total" value="0" />
</form>
As a side note, you should give a try on Angular or Knockout which can help you to achieve those operations.

Get a old value of input before change and change total value to + or -

I want to make points distribution form.
I got 4 inputs type number value 0-100 and total = 100 points. So we can put 25 points in each input. I already get it work to validate inputs number min 0 max 100 and it subtracts from total changed input value.
I have a problem with adding to Total. If user change already changed value I need to make Total + value(before change) and then Total - value(after change).
I don't know how to get value before change.
My html
<input type="number" min="0" max="100" name="1" />
<input type="number" min="0" max="100" name="2" />
<input type="number" min="0" max="100" name="3" />
<input type="number" min="0" max="100" name="4" />
<input type="text" id="Total" name="Total" value="100"/>
My script
$("input[type=number]").keyup(function(event) {
max=100;
min=0;
value=( parseInt($(this).val()));
if(value < min || isNaN(parseInt(value)))
$(this).val(0)
else if(value > max)
$(this).val(100);
else return value;
});
var total, myVal;
$("input[type=number]").change(function(event) {
maxPoints = parseInt($('#Total').val());
myVal = ( parseInt($(this).val()) || 0);
total = maxPoints - myVal;
$('#Total').val(total);
});
If i would be able to save old value to some var i would change .onchange script to something like this and i think it should work. But how i can get old value ?
$("input[type=number]").change(function(event) {
oldValue = ???? - how to get this ? :P
if(oldValue>0){
maxPoints = parseInt($('#Total').val()) + oldValue;
}else{
maxPoints = parseInt($('#Total').val());
}
myVal = ( parseInt($(this).val()) || 0);
total = maxPoints - myVal;
$('#Total').val(total);
});
There is js fiddle how it works now.
Fiddle here
Hi just save the old value like this
$("input[type=number]").change(function(event) {
oldValue = $(this).data('oldvalue');
if(oldValue>0){
maxPoints = parseInt($('#Total').val()) + oldValue;
}else{
maxPoints = parseInt($('#Total').val());
}
myVal = ( parseInt($(this).val()) || 0);
total = maxPoints - myVal;
$(this).data('oldvalue',$(this).val()) // update old value to new value
$('#Total').val(total);
});
<input type="number" min="0" data-oldvalue='0' max="100" name="1" />
<input type="number" min="0" data-oldvalue='0' max="100" name="2" />
<input type="number" min="0" data-oldvalue='0' max="100" name="3" />
<input type="number" min="0" data-oldvalue='0' max="100" name="4" />
<input type="text" id="Total" name="Total" value="100"/>

I am trying to write the array to HTML but it keeps coming up as undefined

<body>
<h1>Find the Even #'s</h1>
<p>Starting Number:</p>
<input id="start" type="number" name="start" min="1" value="1"><br>
<p>Ending Number:</p>
<input id="end" type="number" name="end" min="1" value="1"><br>
<p>Step Number:</p>
<input id="step" type="number" name="step" min="1" value="1"><br>
<button onclick="playGame()">Play Game</button>
<br><br>
<p id="result">#</p>
<script type="text/javascript">
function playGame(){
var startNum = document.getElementById("start").value;
var endNum = document.getElementById("end").value;
var stepNum = document.getElementById("step").value;
var Enumbers = new Array();
for(var i = startNum; i <= endNum; i += stepNum){
if(i % 2 == 0){
Enumbers.push(i);
}
}
document.getElementById("result").innerHTML = Enumbers[];
}
</script>
</body>
If the array is already filled with data of any kind then I am able to write the array data to the html. I feel like the problem is that I am starting with an empty array and I am not filling the array correctly maybe. I just can't seem to figure out what I am doing wrong here.
When using <input> you must remember that the values are strings not numbers (even from type="number"). So you must ensure that the values are converted just in case cohersion isn't working in your favor. I used parseFloat() to convert the string values into numbers, parseInt() and Number are options as well.
Instead of a <p> try displaying results with <output>, these elements are a form control like <input> among it's unique traits is the ability to display it's contents with the .value property like a form control or HTML/Text like a <div> or a <p>, etc.
I added 2 conditions in order to avoid bad input.
Snippet
html {
font: 100 12px/1.3 Consolas;
}
input,
output,
button {
font: inherit;
}
input {
width: 10ch
}
<label>Starting Number: </label>
<input id="start" type="number" name="start" min="1" value="1"><br>
<label>Ending Number: </label>
<input id="end" type="number" name="end" min="2" value="2"><br>
<label>Step Number: </label>
<input id="step" type="number" name="step" min="1" value="1"><br>
<button onclick="playGame()">Play Game</button>
<br><br> #
<output id="result"></output>
<script>
function playGame() {
var start = parseFloat(document.getElementById("start").value);
var end = parseFloat(document.getElementById("end").value);
var step = parseFloat(document.getElementById("step").value);
var even = [];
if (end <= start) {
alert('Starting Number must be less than Ending Number');
return false
} else if (step > (end - start)) {
alert('Step Number cannot exceed ' + (end - start) + ' which is the difference between ' + start + ' and ' + end);
return false
} else
for (let i = start; i <= end; i += step) {
if (i % 2 === 0) {
even.push(i);
}
}
document.getElementById("result").value = even;
}
</script>
Try
document.getElementById("result").innerHTML = Enumbers.toString();
You can't just use Enumbers[].
Note, you can probably omit the .toString() and just use Enumbers. From MDN:
JavaScript calls the toString method automatically when an array is to
be represented as a text value or when an array is referred to in a
string concatenation.

jquery mobile delay slider event

I try to start the slider event when the last value was selected. The idea is, to create something like combination lock.
I've this solution:
<div data-role="page">
<label for="slider1">first</label>
<input data-type="range" name="slider1" id="slider1" value="10" min="0" max="20" />
<br>
<label for="slider2">second</label>
<input type="range" name="slider2" id="slider2" value="10" min="0" max="20" />
<br>
<label for="slider3">third</label>
<input type="range" name="slider3" id="slider3" value="10" min="0" max="20" />
</div>
var seconds = 3,
timer;
$("#slider1, #slider2, #slider3").on("slidestop", function(e) {
var slider1_value = $('#slider1').val();
var slider2_value = $('#slider2').val();
var slider3_value = $('#slider3').val();
var update = function() {
if (slider1_value == 15 && slider2_value == 2 && slider3_value == 2) {
alert("Great!!!");
} else {
alert("Try it again!!!");
}
}
if (timer) clearTimeout(timer);
timer = setTimeout(update, seconds * 1000);
});
Maybe there is a better solution, because the user have to wait for 3 seconds before something happens?
Here is my fiddle
How about this one?
$("#slider1, #slider2, #slider3").on("slidestop", function(e) {
var slider1_value = $('#slider1').val();
var slider2_value = $('#slider2').val();
var slider3_value = $('#slider3').val();
if (slider1_value == 15 && slider2_value == 2 && slider3_value == 2) {
alert("Great!!!");
}
});
EDIT
I have made you a fiddle as well: https://jsfiddle.net/EliteSystemer/7hpbanq9/
My reason for the change is that I would not want to have an error casted each time my combination is wrong, but only when it's correct.
The code above provides automatic verifiation each time one of the sliders are changed. A different approach is to add a button for manual verification. Please let me know if that's what you want, and I'll provide an example for that as well.

Categories