How to edit an HTML slider to make it like this? - javascript

I want to make a slider go from 1-999 stepping by 1, then from 1k to 5m stepping 1k, looking like this
1 2 3------999|1k-2k-3k----999k|1m-2m---5m
I have a code setup that goes from 1k to 5m, I want to add from 1 to 999 in a nice way at the start of the slider, but I cant make it.
<div class="form-group">
<div class="wrapper">
<h5 class="font-alt mt-30">Number of Followers</h5>
<div class="price-input">
<div class="field">
<input readonly
class="input-min" value="0"
name="followers-min">
</div>
<div class="separator">-</div>
<div class="field">
<input readonly
class="input-max" value="INFINITY"
name="followers-max">
</div>
</div>
<div class="slider">
<div class="progress"></div>
</div>
<div class="range-input">
<input style="cursor: pointer;" type="range" class="range-min" min="0"
max="5000000"
value="0"
step="1000">
<input style="cursor: pointer;" type="range" class="range-max" min="0"
max="5000000"
value="5000000"
step="1000">
</div>
</div>
</div>
My current javascript
const rangeInput = document.querySelectorAll(".range-input input"),
priceInput = document.querySelectorAll(".price-input input"),
range = document.querySelectorAll(".slider .progress");
let priceGap = 100_000;
rangeInput.forEach(input => {
input.addEventListener("input", e => {
let minVal = parseInt(rangeInput[0].value),
maxVal = parseInt(rangeInput[1].value);
if ((maxVal - minVal) < priceGap) {
if (e.target.className === "range-min") {
rangeInput[0].value = maxVal - priceGap
} else {
rangeInput[1].value = minVal + priceGap;
}
} else {
let temp = 0
let addition = ""
if (minVal < 1_000) {
temp = String(minVal)
} else if (minVal >= 1_000 && minVal < 10_000) {
temp = String(minVal)[0]
addition = "K"
} else if (minVal >= 10_000 && minVal < 100_000) {
temp = String(minVal)[0] + String(minVal)[1]
addition = "K"
} else if (minVal >= 100_000 && minVal < 1_000_000) {
temp = String(minVal)[0] + String(minVal)[1] + String(minVal)[2]
addition = "K"
} else if (minVal >= 1_000_000) {
temp = String(minVal)[0]
addition = "M"
}
let tempMax = 0
let additionMax = ""
if (maxVal >= 1_000 && maxVal < 10_000) {
tempMax = String(maxVal)[0]
additionMax = "K"
} else if (maxVal >= 10_000 && maxVal < 100_000) {
tempMax = String(maxVal)[0] + String(maxVal)[1]
additionMax = "K"
} else if (maxVal >= 100_000 && maxVal < 1_000_000) {
tempMax = String(maxVal)[0] + String(maxVal)[1] + String(maxVal)[2]
additionMax = "K"
} else if (maxVal >= 1_000_000) {
tempMax = String(maxVal)[0]
additionMax = "M"
}
if (maxVal === 5000000) {
priceInput[1].value = "INFINITY";
} else {
priceInput[1].value = Number(tempMax) + additionMax;
}
priceInput[0].value = Number(temp) + addition;
range[0].style.left = ((minVal / rangeInput[0].max) * 100) + "%";
range[0].style.right = 100 - (maxVal / rangeInput[1].max) * 100 + "%";
}
}
)
;
});
Any idea on how to add from 1-999 at the first of the slider so that it looks a bit like the slider on that website?
https://inflact.com/tools/instagram-search/

You can conditionally adjust the step attribute depending on the current value.
const slider = document.querySelector("#slider");
const output = document.querySelector("output");
slider.addEventListener("input", (e) => {
const value = e.target.value;
if (value < 2500) {
slider.setAttribute("step", 1);
}
else if (value >= 2500 && value < 5000) {
slider.setAttribute("step", 100);
}
else if (value >= 5000) {
slider.setAttribute("step", 500);
}
output.value = e.target.value;
});
<main>
<label for="slider">Slider</label>
<input type="range" name="slider" id="slider" value="0" min="0" max="10000" step="1">
<output name="output" for="slider">0</output>
</main>

Related

Vue-HTML range slider with scaling factor

I need to make a range slider which slide max up to 2000 but with dynamic max values. See the below example for better understanding
The code that came up with is as under. It perform the decrement of range as desired but unable to handle increment
<template>
<div class="slider-wrapper">
<input v-model="current" ref="range" type="range" :min="sliderMin" :max="silderMax" :step="sliderStep" class="slider">
<output class="bubble">{{current}}</output>
</div>
</template>
<script>
export default {
name: 'RangeSlider',
data() {
return {
current: 50,
oldValue:0,
silderMax: 100,
sliderStep: 2.5,
sliderMin: 2.5,
}
},
watch: {
current: function(val, oldVal) {
if(parseFloat(oldVal) > val) {
if(val > 20 && val < 100) {
this.silderMax = 100
} else if (val < 20) {
this.silderMax = 30
}
} else if(parseFloat(oldVal) < val) {
if(val > 7.5 && val < 60) {
this.silderMax = 100
} else if(val > 60 && val < 500) {
this.silderMax = 600;
} else if(val > 500 && val < 1000) {
this.silderMax = 1200;
} else {
this.silderMax = 2000;
}
}
},
},
}
</script>

My "If Else statement" is not working in JavaScript (attempting to perform an equation and if the values are false, alert the user)

Problem:
I am attempting to create an If Else statement, that when the user enters an incorrect value, outside of the range 0 to 80, it alerts the user to input a correct number.
It performs the equation the way I want it to, but when I purposefully input incorrect values, an alert does not appear and the program continues to answer the equation as if nothing ever happened.
The Code:
'use strict';
function calculate() {
var regPay;
var regHours = document.getElementById('regHours').value;
var hourlyRate = document.getElementById('hourlyRate').value;
if (regHours > 0 || regHours < 80) {
regPay = regHours * hourlyRate;
document.getElementById('regPay').value = regPay;
regPay = regPay.toFixed(2);
} else if (regHours < 0 || regHours > 80) {
alert("Enter valid number");
return false;
}
return false;
}
function init() {
document.getElementById('theForm').onsubmit = calculate;
}
window.onload = init;
label {
font-family : Arial, Helvetica, sans-serif;
font-size : 14px;
display : inline-block;
width : 10em;
}
div {
margin : .2em;
}
<form action="#" method="post" id="theForm">
<fieldset>
<legend>Payroll Calculator, find out how much you make!</legend>
<div>
<label for="regHours">Hours Worked (Between 0 and 80)</label>
<input type="text" name="regHours" id="regHours" value="0" required>
</div>
<div>
<label for="hourlyRate">Hourly Rate</label>
<input type="text" name="hourlyRate" id="hourlyRate" value="0.00" required>
</div>
<div>
<label for="regPay">Regular Pay</label>
<input type="text" name="regPay" id="regPay" value="0.00">
</div>
<div>
<input type="submit" value="Calculate" id="submit">
</div>
</fieldset>
</form>
I would write it this way
function calculate() {
'use strict';
var regPay;
var regHours = document.getElementById('regHours').value;
var hourlyRate = document.getElementById('hourlyRate').value;
if (regHours > 0 || regHours < 80) {
regPay = regHours * hourlyRate;
document.getElementById('regPay').value = regPay;
regPay = regPay.toFixed(2);
return true
}
alert ("Enter valid number");
return false;
}
you also need to validate that regHours and hourlyRate hold valid numeric values.
your if condition
if (regHours > 0 || regHours < 80)
is always true
did you mean
if (regHours > 0 && regHours < 80)
After some digging and experimenting, and help from the answers I have found a solution to my problem. I figured I'd add it here (this was the complete end result and the part I was having trouble with was the if then for less than 80):
/*global document: false */
/*jslint devel: true */
function calculate() {
'use strict';
// Input variables
var firstName = document.getElementById('firstName').value,
lastName = document.getElementById('lastName').value,
totHours =
parseFloat(document.getElementById('totHours').value),
regHours = parseFloat(document.getElementById('regHours').value),
overHours = document.getElementById('overHours').value,
hourlyRate = parseFloat(document.getElementById('hourlyRate').value),
fica = document.getElementById('fica').value,
stateTax = document.getElementById('stateTax').value,
fedTax = document.getElementById('fedTax').value;
// Enter in a valid rate
if ((totHours < 0 || totHours > 80) && (hourlyRate < 0 || hourlyRate > 100.0)) {
alert("Please enter valid hours and a valid payrate!");
document.getElementById("theForm").reset("theForm");
} else if (totHours < 0 || totHours > 80) {
//return false;
alert("Please Input valid hours");
document.getElementById("theForm").reset("theForm");
} else if (hourlyRate < 0 || hourlyRate > 100.0) {
alert("Please Input valid hourly rate");
document.getElementById("theForm").reset("theForm");
} else {
//valid
}
// For calculations
if (totHours > 40) {
overHours = 0;
overHours += (totHours - 40);
regHours = 40;
} else if (totHours <= 40) {
regHours = totHours;
}
document.getElementById('regHours').value = regHours;
document.getElementById('overHours').value = overHours;
if (totHours <= 40) {
document.getElementById('regHours').value = regHours;
}
var regPay = (hourlyRate * regHours).toFixed(2),
overtimePay = (overHours * (1.5 * hourlyRate)).toFixed(2),
grossPay = parseFloat(+regPay + +overtimePay).toFixed(2),
totalTax = (parseFloat(+fica + +stateTax + +fedTax) / 100 * grossPay).toFixed(2),
netPay = (grossPay - totalTax).toFixed(2),
employeeName = firstName + " " + lastName;
// output values
document.getElementById('regPay').value = regPay;
document.getElementById('overtimePay').value = overtimePay;
document.getElementById('grossPay').value = grossPay;
document.getElementById('totalTax').value = totalTax;
document.getElementById('employeeName').value = employeeName;
document.getElementById('netPay').value = netPay;
return false;
}
function init() {
'use strict';
document.getElementById('theForm').onsubmit = calculate;
}
window.onload = init;

Calculate by value or percentage

My mortgage calculator includes a down payment field for either a value or a percentage.
If the user enters a value, the percentage is calculated and displayed. If the user enters a percentage, the value is calculated and displayed.
The problem I am having is that once entered, only the value can be modified, not the percentage.
The relevant code is
var Vdown = document.calc.downPayment.value;
if (Vdown == 0 || Vdown == "") {
Vdown = 0;
} else {
var result = (Vdown / VappraisedValue) * 100;
document.calc.downPaymentPercent.value = result;
document.calc.downPayment.value = Vdown;
}
var VdownPercent = document.calc.downPaymentPercent.value;
if (VdownPercent == 0 || VdownPercent == "") {
VdownPercent = 0;
} else {
var percent = (VdownPercent / 100) * VappraisedValue;
document.calc.downPayment.value = percent.toFixed(0);
document.calc.downPaymentPercent.value = VdownPercent;
}
Please see my jsfiddle
function fn(num, places, comma) {
var isNeg = 0;
if (num < 0) {
num = num * -1;
isNeg = 1;
}
var myDecFact = 1;
var myPlaces = 0;
var myZeros = "";
while (myPlaces < places) {
myDecFact = myDecFact * 10;
myPlaces = Number(myPlaces) + Number(1);
myZeros = myZeros + "0";
}
onum = Math.round(num * myDecFact) / myDecFact;
integer = Math.floor(onum);
if (Math.ceil(onum) == integer) {
decimal = myZeros;
} else {
decimal = Math.round((onum - integer) * myDecFact)
}
decimal = decimal.toString();
if (decimal.length < places) {
fillZeroes = places - decimal.length;
for (z = 0; z < fillZeroes; z++) {
decimal = "0" + decimal;
}
}
if (places > 0) {
decimal = "." + decimal;
}
if (comma == 1) {
integer = integer.toString();
var tmpnum = "";
var tmpinteger = "";
var y = 0;
for (x = integer.length; x > 0; x--) {
tmpnum = tmpnum + integer.charAt(x - 1);
y = y + 1;
if (y == 3 & x > 1) {
tmpnum = tmpnum + ",";
y = 0;
}
}
for (x = tmpnum.length; x > 0; x--) {
tmpinteger = tmpinteger + tmpnum.charAt(x - 1);
}
finNum = tmpinteger + "" + decimal;
} else {
finNum = integer + "" + decimal;
}
if (isNeg == 1) {
finNum = "-" + finNum;
}
return finNum;
}
function sn(num) {
num = num.toString();
var len = num.length;
var rnum = "";
var test = "";
var j = 0;
var b = num.substring(0, 1);
if (b == "-") {
rnum = "-";
}
for (i = 0; i <= len; i++) {
b = num.substring(i, i + 1);
if (b == "0" || b == "1" || b == "2" || b == "3" || b == "4" || b == "5" || b == "6" || b == "7" || b == "8" || b == "9" || b == ".") {
rnum = rnum + "" + b;
}
}
if (rnum == "" || rnum == "-") {
rnum = 0;
}
rnum = Number(rnum);
return rnum;
}
function computeForm(form) {
var VappraisedValue = document.calc.appraisedValue.value;
var Vdown = document.calc.downPayment.value;
if (Vdown == 0 || Vdown == "") {
Vdown = 0;
} else {
var result = (Vdown / VappraisedValue) * 100;
document.calc.downPaymentPercent.value = result;
document.calc.downPayment.value = Vdown;
}
var VdownPercent = document.calc.downPaymentPercent.value;
if (VdownPercent == 0 || VdownPercent == "") {
VdownPercent = 0;
} else {
var percent = (VdownPercent / 100) * VappraisedValue;
document.calc.downPayment.value = percent.toFixed(0);
document.calc.downPaymentPercent.value = VdownPercent;
}
}
<form name="calc" method="post" action="#">
<table border='1' cellpadding='4' cellspacing='0'>
<tbody>
<tr>
<td nowrap>
Home value:
</td>
<td align="center">
<span class="input-group-addon">$</span>
<input id="appraised-value" type="number" min="0" max="10000000" step="25000" class="form-control" name="appraisedValue" onKeyUp="computeForm(this.form)" value="0" onfocus="if(this.value==this.defaultValue)this.value=''" onblur="if(this.value=='')this.value=this.defaultValue">
</td>
</tr>
<tr>
<td nowrap>
Down payment:
</td>
<td align="center">
<span class="input-group-addon">$</span>
<input id="down-payment" type="number" min="0" max="10000000" step="5000" class="form-control" name="downPayment" onKeyUp="computeForm(this.form)" value="0" onfocus="if(this.value==this.defaultValue)this.value=''">
<input id="down-payment-percent" type="number" min="0" max="100" step="1" class="form-control" name="downPaymentPercent" onKeyUp="computeForm(this.form)" value="0" onfocus="if(this.value==this.defaultValue)this.value=''">
<span class="input-group-addon">%</span>
</td>
</tr>
</tbody>
</table>
</form>
The issue is the way you are updating the Payment / Percent values - every time either value is updated, the code in computeForm uses the value in Payment to update Percent, and only then the value of Percent (just updated) is used to set Payment. As a result, whatever is in Payment will always win.
A couple of options to get it working the way you want it to:
You could pass a variable in the "onKeyUp" events of Payment and Percent that tells ComputeForm which to use to update the other, using an if(which === "pmt") { [code_to_update_payment] } else { [code_to_update_pct] } type construct.
You could break out the update code into two separate functions, function updatePmt() { } function updatePct() { } and then call each from the respective "onKeyUp" method in the HTML.
Either should work equally well to solve the behavior you are experiencing.

How to set custom step input value?

I need to change the step according to input number value but it does not work right. If the value is 20 step is 2 but it gives 21, 23, 25... instead of 22, 24, 26... Why? How can I solve it?
$(function() {
$('#points').on('input change', function() {
var element = $('#points'),
deger = element.val(),
adim;
// Set rules here
if (deger < 20) {
adim = 1;
} else if (deger >= 20 && deger < 50) {
adim = 2;
} else if (deger >= 50 && deger < 100) {
adim = 5;
} else if (deger >= 100 && deger < 200) {
adim = 10;
} else {
adim = 50;
}
element.attr('step', adim);
$('#deger').text(deger);
$('#adim').text(adim);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!doctype html>
<html>
<div>
Value: <span id="deger"></span>
</div>
<div>
Current step: <span id="adim"></span>
</div>
<div>
<input id="points" type="number" step="4" value="12" min="1" max="10000" />
</div>
Apparently, the problem is the min attribute. Since you have min="1" when you are at 20 it goes first on 21 (because min is 1) and then starts with the correct step.
To solve simply update the min attribute also.
element.attr('step', adim);
element.attr('min', adim);
With this you can go backwards
$(function() {
var adim;
$('#points').on('input', function() {
var element = $('#points'),
deger = element.val()
// Set rules here
if (deger < 20) {
adim = 1;
} else if (deger == 20) {
adim = adim === 2 ? 1 : 2;
} else if (deger == 50) {
adim = adim == 5 ? 2 : 5;
} else if (deger == 100) {
adim = adim == 10 ? 5 : 10;
} else if (deger == 200) {
adim = adim == 50 ? 10 : 50;
}
element.attr('step', adim);
element.attr('min', adim);
$('#deger').text(deger);
$('#adim').text(adim);
});
});

Credit card validation in javascript

I wrote this code to validate credit card digits, saved it as an html file. It's not working though.
<html>
<head>
<script>
function mod10_check(val){
var nondigits = new RegExp(/[^0-9]+/g);
var number = val.replace(nondigits,'');
var pos, digit, i, sub_total, sum = 0;
var strlen = number.length;
if(strlen < 13){ return false; }
for(i=0;i
<strlen;i++){
pos = strlen - i;
digit = parseInt(number.substring(pos - 1, pos));
if(i % 2 == 1){
sub_total = digit * 2;
if(sub_total > 9){
sub_total = 1 + (sub_total - 10);
}
} else {
sub_total = digit;
}
sum += sub_total;
}
if(sum > 0 && sum % 10 == 0){
return true;
}
return false;
}
</script>
</head>
<body>
<form>
<input type="text"
name="cc_number"
onblur="if(mod10_check(this.value)){$('#cc_error').hide(); } else { $('#cc_error').show(); }"
value="" />
<span id="cc_er`enter code here`ror" style="display:none;">The card number is invalid.</span>
</form>
</body>
</html>
Does not validate value entered in the textbox. When the textbox goes out of focus message is not shown.Not willing to use any third party plugin.What is wrong with this code?
Try re-writing your inline code as an event handler.
var ccInp = document.getElementById('cc_no');
ccInp.addEventListener('blur', function() {
if(!mod10_check(ccInp.value)) {
document.getElementById('cc_error').style.display = '';
}
});
function mod10_check(val){
var nondigits = new RegExp(/[^0-9]+/g);
var number = val.replace(nondigits,'');
var pos, digit, i, sub_total, sum = 0;
var strlen = number.length;
if(strlen < 13){ return false; }
for(i=0;i
<strlen;i++){
pos = strlen - i;
digit = parseInt(number.substring(pos - 1, pos));
if(i % 2 == 1){
sub_total = digit * 2;
if(sub_total > 9){
sub_total = 1 + (sub_total - 10);
}
} else {
sub_total = digit;
}
sum += sub_total;
}
if(sum > 0 && sum % 10 == 0){
return true;
}
return false;
}
<form>
<input type="text"
name="cc_number"
value=""
id="cc_no"/>
<span id="cc_error" style="display:none;">The card number is invalid.</span>
</form>
jsFiddle: http://jsfiddle.net/8kyhtny2/

Categories