Change range element's step depending on it's value - javascript

Right now I have this range element:
<input type="range"
onchange= "calculate();"
id="sumRange"
min="50000"
max="500000"
value="50000"
step= "50000"/>
I want its "step" to change depending on its value. For example, if the value is less than 200000 then step = 5000, if more than 200000 then step= 50000.
How can I do that? Do I create a function with simple "if" statements and make it run onchange of the range?
All example i've seen involve jQuery or something else, can i do this without...that?

See below, change the ranges as needed
function calculate() {
var input = document.getElementById('sumRange');
var val = input.value;
var newStep;
if (val < 100000) {
newStep = 10;
} else if (val < 150000) {
newStep = 20;
} else if (val < 200000) {
newStep = 30;
} else if (val < 250000) {
newStep = 40;
} else {
newStep = 50;
}
input.step = newStep;
}
<input type="range"
onchange= "calculate();"
id="sumRange"
min="50000"
max="500000"
value="50000"
step= "50000"/>

here is what you can do in your calculate function, using jquery
calculate = function() {
if ($('#sumRange').attr('value') < 200000 ) {
$('#sumRange').attr('step',5000);
} else {
$('#sumRange').attr('step',50000);
}

var sumRange = document.getElementById(“sumRange”);
sumRange.oninput = function(){
var value = this.value;
if (value > 20000) {
this.step = 50000;
} else {
this.step=5000;
}

Related

Parsing Strings and Integers in JavaScript

I am new to JavaScript and HTML and am hoping someone can notice what I am doing wrong (I'm sure it is probably something small that I am just missing). I have been looking at this for a while, and I cannot seem to figure it out.
The problem is that branch #2 (identified in the comment within the code) is returning NaN for the houseVal which is supposed to return either sf for single-family or tw for townhouse/condo.
I have a JavaScript form I am making. Here it is:
function getPrice() {
var form = document.getElementById("calc");
var out = form.elements["z"];
//get numbers
var sqftVal = parseInt(form.elements["sqft"].value);
var bathsVal = parseInt(form.elements["baths"].value);
var builtVal = parseInt(form.elements["built"].value);
var lotVal = parseInt(form.elements["lot"].value);
for (i = 0; i < document.forms[0].zipcode.length; i++) {
if (document.forms[0].zipcode[i].checked) {
var zipVal = parseInt(document.forms[0].zipcode[i].value);
}
}
for (i = 0; i < document.forms[0].gar.length; i++) {
if (document.forms[0].gar[i].checked) {
var garageVal = parseInt(document.forms[0].gar[i].value);
}
}
for (i = 0; i < document.forms[0].housetype.length; i++) {
if (document.forms[0].housetype[i].checked) {
var houseVal = parseInt(document.forms[0].housetype[i].value);
}
}
if (zipVal == "47") {
if (garageVal == "2") {
if (houseVal == "sf") {
out.value = 1;
}
else { //townhouse
out.value = houseVal; // <------ PROBLEM: returns NaN <------------
}
}
else { //garage == 3
if (houseVal == "sf") {
out.value = 3;
}
else { //townhouse
out.value = 4;
}
}
}
else { //zip == 20148
if (garageVal == "2") {
if (houseVal == "sf") {
out.value = 5;
}
else { //townhouse
out.value = 6;
}
}
else { //garage == 3
if (houseVal == "sf") {
out.value = 7;
}
else { //townhouse
out.value = 8;
}
}
}
}
</script>
and here is the Home Type (e.g., Single Family or Townhouse/Condo) part of the form.
...
<fieldset>
<legend>House Type</legend>
<div>
<input type="radio" id="sf" name="housetype" value="sf" />
<label for="sf">Single Family</label>
</div>
<div>
<input type="radio" id="tw" name="housetype" value="tw" />
<label for="tw">Townhouse/Condo</label>
</div>
</fieldset>
...
It looks like in your javascript code you are trying to convert the houseVal to an integer though it's only ever "sf" or "tw"
If you change the following block:
for (i = 0; i < document.forms[0].housetype.length; i++) {
if (document.forms[0].housetype[i].checked) {
var houseVal = parseInt(document.forms[0].housetype[i].value);
}
}
To:
for (i = 0; i < document.forms[0].housetype.length; i++) {
if (document.forms[0].housetype[i].checked) {
var houseVal = document.forms[0].housetype[i].value;
}
}
You should be good
Your value attributes for each radio button are letter based strings. You cannot feasibly use parseInt on letter-based strings .
var houseVal = parseInt(document.forms[0].housetype[i].value);
This is going to cause you issues.

Type range not working in IE11 while using jQuery

I have 3 similar type range sliders on my page that work in browsers such as Chrome, Opera and Firefox. But when I try and use the slider in IE11 and below or Edge it doesn't want to slide.
HTML:
<div class="filterItem">
<section id="preperation" class="range-slider">
<p class="sliderText">Preperation Time (minutes)</p>
<span class="rangeValues"></span>
<inputclass="minSlider" value="0" min="0" max="61" step="1" type="range"
onchange="filter()">
<inputclass="maxSlider" value="61" min="0" max="61" step="1" type="range"
onchange="filter()">
</section>
</div>
jQuery:
function getVals() {
// Get slider values
console.log("values")
var parent = this.parentNode;
var slides = parent.getElementsByTagName("input");
var slide1 = parseFloat(slides[0].value);
var slide2 = parseFloat(slides[1].value);
// Neither slider will clip the other, so make sure we determine which is larger
if (slide1 > slide2) {
var tmp = slide2;
slide2 = slide1;
slide1 = tmp;
}
var slider = parent.getElementsByClassName('sliderText')[0].innerHTML;
var displayElement = parent.getElementsByClassName("rangeValues")[0];
var max = 0
if (slider == 'Preperation Time (minutes)') {
max = 60;
} else if (slider == 'Cooking Time (minutes)') {
max = 90;
} else {
max = 99999999
}
if (slide2 > max) {
slide2 = String(max) + '+';
}
displayElement.innerHTML = slide1 + " - " + slide2;
}
This is some more jQuery that loads the sliders in onload.
window.onload = function() {
// Set the sliders for the current values in the URL
if (location.search) {
var urlParams = new URLSearchParams(window.location.search);
var entries = urlParams.entries();
for (pair of entries) {
if (pair[0] == 'q') {
document.querySelector('input#searchBarMain').value = pair[1]
document.querySelector('input#filterSearch').value = pair[1]
}
if (pair[0] == 'min_cook_time') {
document.querySelector('#cooking>input.minSlider').value = pair[1]
}
if (pair[0] == 'max_cook_time') {
document.querySelector('#cooking>input.maxSlider').value = pair[1]
}
if (pair[0] == 'min_prep_time') {
document.querySelector('#preperation>input.minSlider').value = pair[1]
}
if (pair[0] == 'max_prep_time') {
document.querySelector('#preperation>input.maxSlider').value = pair[1]
}
if (pair[0] == 'min_servings') {
document.querySelector('#servings>input.minSlider').value = pair[1]
}
if (pair[0] == 'max_servings') {
document.querySelector('#servings>input.maxSlider').value = pair[1]
}
}
}
// Initialize Sliders
var sliderSections = document.getElementsByClassName("range-slider");
for (var x = 0; x < sliderSections.length; x++) {
var sliders = sliderSections[x].getElementsByTagName("input");
for (var y = 0; y < sliders.length; y++) {
if (sliders[y].type === "range") {
sliders[y].oninput = getVals;
// Manually trigger event first time to display values
sliders[y].oninput();
}
}
}
}
Have tried looking at other similar questions on Stack Overflow and they don't work.

Check if the sum of fields are greater than 100?

What I try to achieve to give alert if the sum of first values are greater than 100 if not third value has to be calculated like this;
3th textbox= 100- 1st textbox- 2th textbox
It works well at the beginning. When I type 100 for 1st textbox then 20 for 2nd I get error then I enter 80-30 I get again alert but then third times when I enter 50-30 I again get error but actually it shouldnt give error it should write in third textbox 20
$(document).ready(function() {
// calc
jQuery("#custom-419").on("change", function() {
var vorOrt = $(this).val();
jQuery("#custom-420").on("change", function() {
var vorOrt2 = $(this).val();
var sum = 0;
sum += parseInt(vorOrt);
sum += parseInt(vorOrt2);
console.log($('#sum').val());
if (sum <= 100) {
var onWeb = 100 - vorOrt;
onWeb = onWeb - vorOrt2;
jQuery("#421").val(onWeb);
} else {
window.alert("The sum of values can not be more than 100!");
$('#custom-419').val("");
$('#custom-420').val("");
$('#custom-421').val("");
}
});
})
});
Because all the other answers contains jQuery, I though it may be helpful to provide a vanilla JavaScript solution. Keep in mind that solution is for modern browser only!
function calc() {
const counters = [...document.querySelectorAll('.counter')];
const total = document.querySelector('.total');
const sum = counters.reduce((a, b) => a += parseInt(b.value) || 0, 0);
total.value = sum;
if (sum <= 100) return;
alert("The sum of values can not be more than 100!");
counters.forEach(x => x.value = '');
total.value = '';
}
[].forEach.call(document.querySelectorAll('.counter'), x => x.addEventListener('keyup', calc));
<div>
result has to be less then or equal 100
</div>
<input class="counter" id="#custom-419" /> +
<input class="counter" id="#custom-420" /> =
<input class="total" id="#custom-421" disabled />
Explanation
Because you didn't show us your current html, I made it simple. So no explanation required I guess.
What happens in that JS solution is pretty straight forward.
In the last line both input with the call counter are getting an EventListener to fire on keyup. You may keep the change event instead...
In the calc function all values of the counters get parsed to int and aggregated to sum. The rest of the code is nothing special.
As the above solution is for modern browsers only (ES6+), here are two more for older browsers:
IE11+ Support (Demo)
function calc() {
const counters = document.querySelectorAll('.counter');
const total = document.querySelector('.total');
const sum = Array.prototype.reduce.call(counters, function(a, b) {
return a += parseInt(b.value) || 0;
}, 0);
total.value = sum;
if (sum <= 100) return;
alert("The sum of values can not be more than 100!");
Array.prototype.forEach.call(counters, function(x) {
x.value = '';
});
total.value = '';
}
Array.prototype.forEach.call(document.querySelectorAll('.counter'), function(x) {
x.addEventListener('keyup', calc);
});
IE9+ Support (Demo)
I made two more function for this example to make it a bit more readable.
function calc() {
var counters = document.querySelectorAll('.counter');
var total = document.querySelector('.total');
var sum = getSum(counters);
total.value = sum;
if (sum <= 100) return;
alert("The sum of values can not be more than 100!");
clearCounters(counters);
total.value = '';
}
function getSum(counters) {
var result = 0;
for(var i = 0; i < counters.length; i++) {
result += parseInt(counters[i].value) || 0;
}
return result;
}
function clearCounters(counters) {
for(var i = 0; i < counters.length; i++) {
counters[i].value = '';
}
}
var _counters = document.querySelectorAll('.counter');
for(var i = 0; i < _counters.length; i++) {
_counters[i].addEventListener('keyup', calc);
}
Why nesting the 2 event functions ?
Try this :
var vorOrt = 0;
var vorOrt2 = 0;
$(document).ready(function() {
$('#custom-419').on('change', function() {
vorOrt = $(this).val();
checkInputs();
});
$('#custom-420').on('change', function() {
vorOrt2 = $(this).val();
checkInputs();
});
});
function checkInputs() {
var sum = 0;
sum += parseInt(vorOrt, 10);
sum += parseInt(vorOrt2, 10);
if (sum <= 100) {
var onWeb = 100 - vorOrt - vorOrt2;
$("#custom-421").val(onWeb);
} else {
window.alert('The sum of values can not be more than 100!');
$('#custom-419').val('');
$('#custom-420').val('');
$('#custom-421').val('');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="counter" id="custom-419" type="number" />
<input class="counter" id="custom-420" type="number" />
<input class="total" id="custom-421" type="number" />
Once change function is inside the other, which is not necessary, Also reset the value of sum when alert is thrown
$(document).ready(function() {
var sum = 0; // initializing sum
function calSum(val) {
sum += val; // will add the values
console.log(sum)
if (sum <= 100) {
var onWeb = 100 - sum;
$("#custom-421").val(onWeb);
} else {
alert("The sum of values can not be more than 100!");
$('#custom-419').val("");
$('#custom-420').val("");
$('#custom-421').val("");
sum = 0;
}
}
$("#custom-419").on("change", function() {
calSum(parseInt($(this).val(), 10));
});
$("#custom-420").on("change", function() {
calSum(parseInt($(this).val(), 10));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="custom-419">
<input type="text" id="custom-420">
<input type="text" id="custom-421">
Look at the following solution. It uses jQuery's each.
What I did is attach the same function to every input by using a descriptive class name: counter. We can easily get all the input using the selector input.counter and add an onchange event with only one line of code.
After that the generic function testIfMoreThanHundred will iterate over all the element using each and sum the values into a variable.
after that it's just a simple if check to see if the value if more than a hundred.
$(document).ready(function() {
// calc
$("input.counter").on("change", testIfMoreThanHundred);
});
//let's make a generic function shall we:
function testIfMoreThanHundred() {
var sum = 0;
//get the elements and use each to iterate over them
$("input.counter").each(function() {
var number = parseInt($(this).val(), 10);
//test if value is a number, if not use 0
if (!isNaN(number)) {
sum += parseInt($(this).val(), 10);
} else {
sum += 0;
}
});
if (sum > 100)
{
alert("The sum can't be greater than a 100");
$("input.counter").val(""); //empty the values
$("input.total").val("");
}
else
{
$("input.total").val(100 - sum); //show value in third box
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="counter" id="custom-419" type="number" />
<input class="counter" id="custom-420" type="number" />
<input class="total" id="custom-421" type="number" />

Value condition not working as expected

I have number of inputs and I want to set a minimum value of each input section. For example, I have set a minimum input value of 100. So if the value of any input is less than 100 from all the inputs it will show an error. Otherwise if value of all the inputs is greater than or equal to 100 it will show the success message.
In my case if I enter less than value in an input it will show error but with this less value if I enter greater value in other input it show success message.
<div class="color-quantity not-selected-inputs selected-input-wrap">
<input type="text" class="custom_small" name="custom_small" onkeydown="return myFunction(event);">
</div>
<div class="color-quantity not-selected-inputs selected-input-wrap">
<input type="text" class="custom_medium" name="custom_medium" onkeydown="return myFunction(event);">
</div>
<input type="text" class="custom_large" name="custom_large" onkeydown="return myFunction(event);">
</div>
jQuery('.selected-input-wrap > input').map(function () {
var total = 0;
jQuery('input', this).each(function () {
total += this.value * 1;
});
if (parseInt(total) <= 99) {
jQuery(".select-quantity").html('<p>Please select at least 100 for each color</p>');
} else if (parseInt(total) >= 100) {
jQuery(".select-quantity").html('<p>Success</p>');
}
Please have a look at the code and help me find out the issue
There's a couple of issues.
You should declare total outside the loop otherwise you reset it back to 0 on each iteration.
You should also use a single each() call to loop over a set of elements, as map() is intended to be used to create an array from those elements.
You only need to call parseInt() once when you add the value to total
Your else if condition is redundant and can be replaced by just else, or even a ternary as below.
Try this:
jQuery(function($) {
var total = 0;
$('.selected-input-wrap > input').each(function () {
total += parseInt(this.value, 10);
});
var msg = total >= 100 ? '<p>Success</p>' : '<p>Please select at least 100 for each color</p>';
$(".select-quantity").html(msg);
});
The total variable is looping through all the inputs and only once its returning according to your code. Try closing the each loop after the if-else condition and check once.
jQuery('.selected-input-wrap > input').map(function () {
var total = 0;
jQuery('input', this).each(function () {
total += this.value * 1;
if (parseInt(total) <= 99) {
jQuery(".select-quantity").html('<p>Please select at least 100 for each color</p>');
} else if (parseInt(total) >= 100) {
jQuery(".select-quantity").html('<p>Success</p>');
}
});
})
You can use the following jquery code :-
jQuery('.selected-input-wrap > input').map(function () {
var total = 0;
jQuery('input').each(function () {
total = $(this).val();
if (parseInt(total) <= 99) {
jQuery(".select-quantity").html('<p>Please select at least 100 for each color</p>');
}
else if (parseInt(total) >= 100) {
jQuery(".select-quantity").html('<p>Success</p>');
}
});
});
It may help you.
Try this.
var MIN = 100, value = 0;
jQuery('.selected-input-wrap > input').each(function (idx,el) {
value += parseInt(el.value);
});
if (value < MIN) {
jQuery(".select-quantity").html('<p>Please select at least 100 for each color</p>');
} else {
jQuery(".select-quantity").html('<p>Success</p>');
}
In My Case i have solved the issue as follows:
var total = 0;
var array_total = new Array();
jQuery('.selected-input-wrap > input').each(function(index, value) {
jQuery( ".right-minimu").remove();
var total = jQuery(this).val();
console.log("Total Value : " + total);
if (total != '') {
var t_array = array_total.push(total);
}
console.log('Total Array : ' + array_total);
});
/******** make array unique *************/
var unique_total = [];
jQuery.each(array_total, function(i, el) {
if (jQuery.inArray(el, unique_total) === -1)
unique_total.push(el);
});
var current_urls = jQuery(location).attr('href');
var rest = current_urls.substr(37, 9); //
var current_urls = jQuery(location).attr('href');
var rest_2 = current_urls.substr(37, 18);
var rest_3 = current_urls.substr(37, 15);
var rest_4 = current_urls.substr(37, 8);
jQuery.each(unique_total, function(key, total) {
for (var i = 0; i <= unique_total.length; i++) {
if(rest == "bracelets") {
if (parseInt(unique_total[i]) <= 99) {
jQuery(".select-quantity").css("display", "block");
jQuery(".select-quantity").html('<p>Please select at least 100 for each color</p>');
jQuery( "#order-overview-table table" ).css("display" , "none") ;
jQuery( "#order-overview-table").append("<p class='right-minimu'>Please select at least 100 for each color</p>") ;
jQuery('.btn-cart').removeAttr("onclick");
return false;
} else if (parseInt(unique_total[i]) >= 100) {
jQuery(".select-quantity").css("display", "none");
jQuery('.btn-cart').attr('onClick', 'productAddToCartForm.submit(this);');
jQuery(".select-quantity").html('<p>Products Added</p>').delay(4000);
}
}

javascript countdown with showing milliseconds

I want to do a count down and want to show like format as Minutes:Seconds:Milliseconds. I made a count down with jquery plug-in countdown but it shows just Minutes:Seconds format.
Is there any way to make it right?
Many Thanks!
Hi guys I have developed a code for my self use the following code
counter for 20 seconds
var _STOP =0;
var value=1999;
function settimer()
{
var svalue = value.toString();
if(svalue.length == 3)
svalue = '0'+svalue;
else if(svalue.length == 2)
svalue = '00'+svalue;
else if(svalue.length == 1)
svalue = '000'+svalue;
else if(value == 0)
svalue = '0000';
document.getElementById('cn1').innerHTML = svalue[0];
document.getElementById('cn2').innerHTML = svalue[1];
document.getElementById('cn3').innerHTML = svalue[2];
document.getElementById('cn4').innerHTML = svalue[3];
value--;
if (_STOP==0 && value>=0) setTimeout("settimer();", 10);
}
setTimeout("settimer()", 10);
Try this: http://jsfiddle.net/aamir/TaHtz/76/
HTML:
<div id="timer"></div>
​
JS:
var el = document.getElementById('timer');
var milliSecondsTime = 10000;
var timer;
el.innerHTML = milliSecondsTime/1000;
timer = setInterval(function(){
milliSecondsTime = milliSecondsTime - 1000;
if(milliSecondsTime/1000 == 0) {
clearTimeout(timer);
el.innerHTML = 'BOOOOM';
}
else {
el.innerHTML = milliSecondsTime/1000;
}
},1000);
​
If you want to make your own timer.
read this earlier question
How to create a JQuery Clock / Timer
Try setting the format parameter - http://keith-wood.name/countdownRef.html#format
On further reading, this plugin doesn't do milliseconds. At this point, you either have to edit the actual plugin code or find a new plugin.
I completely agree with #Matt Ball's comment.It may also cause the browser to crash.
Why don't you try this solution instead
jQuery 1 minute countdown with milliseconds and callback
I did it like this (generic counter from N to X (X > N)):
var dynamicCounterAddNewValue = 20;
var currentDynamicUpdater;
function dynamicCounterForValueForControlUpdater(_updaterData) {
_updaterData.from += dynamicCounterAddNewValue;
if (_updaterData.from > _updaterData.to) {
_updaterData.from = _updaterData.to;
}
_updaterData.c.html(_updaterData.from.toString());
if (_updaterData.from < _updaterData.to) {
currentDynamicUpdater = setTimeout(
dynamicCounterForValueForControlUpdater,
10,
{
c: _updaterData.c,
from: _updaterData.from,
to: _updaterData.to
}
);
}
else {
clearTimeout(currentDynamicUpdater);
}
return;
}
// _c -> jQuery object (div,span)
// _from -> starting number
// _to -> ending number
function dynamicCounterForValueForControl(_c, _from, _to) {
clearTimeout(currentDynamicUpdater);
dynamicCounterForValueForControlUpdater(
{
c: _c,
from: _from,
to: _to
}
);
return;
}
EDIT: Updated version (more flexible - for N elements one after another):
(input element is Array of elements for making them dynamic-counts)
var dynamicCounterTimeout = 10;
var currentDynamicUpdater;
function odcArray(_odca) {
this.odca = _odca;
return;
}
function odc(_c, _from, _to) {
this.c = _c; // $('#control_id')
this.from = _from; // e.g. N
this.to = _to; // e.g. M => (M >= N)
var di = parseInt(_to / 45, 10);
if (di < 1) {
di = 1;
}
this.dynamicInc = di;
return;
}
function dynamicCounterForValueForControlUpdater(_odca) {
if (
_odca.odca === null
||
!_odca.odca.length
) {
clearTimeout(currentDynamicUpdater);
return;
}
var o = _odca.odca[0];
o.from += o.dynamicInc;
if (o.from > o.to) {
o.from = o.to;
_odca.odca.shift(); // Remove first element
}
o.c.html(o.from.toString());
currentDynamicUpdater = setTimeout(
dynamicCounterForValueForControlUpdater,
dynamicCounterTimeout,
_odca
);
return;
}
function dynamicCounterForValueForControl(_odca) {
clearTimeout(currentDynamicUpdater);
// SETUP all counters to default
for (var i = 0; i < _odca.odca.length; i++) {
_odca.odca[i].c.html(_odca.odca[i].from.toString());
}
dynamicCounterForValueForControlUpdater(
_odca
);
return;
}

Categories