Javascript combined value sliders - javascript

The solutions I have found are jQuery and can't understand them yet.
Anyways, I have a couple of sliders and I want to make it so that their combined max values are always less than a predefined value (variable called available in this case). So that when I change a slider, the max values of the other sliders change.
var available = 10;
var max = 0;
var old = 0;
window.onload = function () {
var sliders = document.getElementsByTagName("input");
var numSliders = sliders.length;
for (i = 0; i < numSliders; i++) {
//Define all sliders?
sliders.item(i).max = available;
document.getElementById(sliders.item(i).id + "val").innerHTML = sliders.item(i).value;
document.getElementById(sliders.item(i).id + "max").innerHTML = sliders.item(i).max;
sliders.item(i).addEventListener("input", function(){
updateSliders();
Slider(this);
})
}
}
function updateSliders() {
var sliders = document.getElementsByTagName("input");
var numSliders = sliders.length;
for (i = 0; i < numSliders; i++)
{
document.getElementById(sliders.item(i).id + "val").innerHTML = sliders.item(i).value;
document.getElementById(sliders.item(i).id + "max").innerHTML = sliders.item(i).max;
}
};
function Slider(active) {
//Get weird set thingy of all sliders
var sliderObject = document.getElementsByTagName("input");
var numberSliders = sliderObject.length;
var total = 0;
//Work out what is being displayed
for(i=0;i<numberSliders;i++)
{
var value = sliderObject.item(i).value;
total += parseInt(value);
}
for(i=0;i<numberSliders;i++)
{
var value = sliderObject.item(i).value;
max = available - value;
if(sliderObject.item(i) != active)
{
console.log("total = " + total);
console.log("old = " + old);
var difference = total - old;
console.log("Difference = " + difference);
sliderObject.item(i).max = sliderObject.item(i).max - (total - old);
}
}
old = total;
}
<div class="sliderContainer">
<input id="slider1" type="range" value=0> <span id="slider1val">0</span>/<span id="slider1max">0</span>
<br>
<input id="slider2" type="range" value=0> <span id="slider2val">0</span>/<span id="slider2max">0</span>
<br>
<input id="slider3" type="range" value=0> <span id="slider3val">0</span>/<span id="slider3max">0</span>
<br> </div>
It kinda works, but the numbers it displays are wrong or something?
Thanks for your time.

One thing you need to change is the order of function calls executed on input event. Slider(this) should be first.
Here is your fixed code: https://codepen.io/kejt/pen/xgoqeX

Related

How to set data range based on radio button selected

I need to make the min and max variables change depending on the radio button checked. Currently my HTML looks like
<input type="radio" name="type" class="frequency" value="0">
<label for="0">1960-2099</option>
<input type="radio" name="type" class="frequency" value="1">
<label for="1">Other range, e.g. 1970-2000</option>
And the js to generate the year range looks like
$(".frequency").click(function(){
var $msd = $("#startDate");
var $month = $("#startMonth");
var $year = $("#startYear");
min = 1960
max = 2099
$('select').change(function () {
var val = "01/" + $month.val() + "/" + $year.val();
$msd.val(val);
});
select = document.getElementById('startYear');
for (var i = min; i<=max; i++){
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = i;
select.appendChild(opt);
}
var $mfd = $("#finalDate");
var $monthf = $("#finalMonth");
var $yearf = $("#finalYear");
$('select').change(function () {
var val = "01/" + $monthf.val() + "/" + $yearf.val();
$mfd.val(val);
});
selectf = document.getElementById('finalYear');
for (var i = min; i<=max; i++){
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = i;
selectf.appendChild(opt);
}
});
if you want to make changes in min and max value depending on the radio button click then see if my solution works for you or not.
<script>
$(document).ready(function() {
$(".frequency").click(function() {
let val = $(this).val();
let min = 0;
let max = 0;
if (val == 0) {
// 0 for 1960-2099
// code goes here
// assign value to min and max variable here
}
if (val == 1) {
// 1 for Other range or whatever the range you want
// code goes here
// assign value to min and max variable here
}
});
});
</script>
Add an event to the Event Listener, then:
$(".frequency").click(function(event){
var $msd = $("#startDate");
var $month = $("#startMonth");
var $year = $("#startYear");
let min;
let max;
if (event.target.value === 0) {
min = 1960
max = 2099
} else {
min = 1970
max = 2000
}
I don't know Jquery, but it's pretty straightforward also in plain JS.

How to change number inside of div class and update it?

I'm trying to change the existing HTML code on a site. See the example below:
var multiplier = 1.5;
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 0
})
//for first two occurences
var priceEls = document.getElementsByClassName("price");
for (var i = 0; i < priceEls.length; i++) {
var price = priceEls[i].innerText;
var priceN = getNumber(price)*multiplier;
alert("Price: " + formatter.format(priceN));
}
//for last occurence
var priceEls = document.getElementsByClassName("column--container value-item");
for (var i = 0; i < priceEls.length; i++) {
var price = priceEls[i].innerText;
//alert("Price: " + price);
var priceN = getNumber(price)*multiplier;
alert("Price: " + formatter.format(priceN));
}
function getNumber(myString) {
var numb = myString.match(/\d/g);
numb = numb.join("");
//alert (numb);
return(parseInt(numb));
}
<div class="price">$2,000</div>
<div class="price">
<span>$</span>
3,000
</div>
<div class="column--container value-item">
<span class="text-semibold-xs">Price</span>
$1,500
</div>
How do I update the HTML code with those new values?
One thing you can do after calculating the new prices is set the innerText of an element with the text you are using on the alert. So one of your loops can look like this
for (var i = 0; i < priceEls.length; i++) {
var price = priceEls[i].innerText;
var priceN = getNumber(price)*multiplier;
priceEls[i].innerText = "Price: " + formatter.format(priceN);
}
I would recomend using forEach for looping instead of for.

HTML not changing from JavaScript script

I am trying to make a basic Average Calculator in HTML and JavaScript. I have the input field and buttons in HTML and the averaging and Reset functions in JavaScript. I cannot find where my problem is.
HTML Code:
<section class="script">
<script src="avg.js"></script>
<input type="number" id="inputVal" placeholder="Input Value..."></number><br>
<button id="Btn_Avg" onclick="AddFunc(inputVal.Value)">Average</button>
<button id="Btn_Rst" onclick="ResetFunc()">Reset</button>
<p>Average: </p><p id="average">OK</p>
</section>
JavaScript script (avg.js):
global var count = 0;
global var total = 0;
global var avg = 0;
global var result = document.getElementById("average");
result.textContent = 0;
function AddFunc(value){
total += value;
count += 1;
avg = total / count;
result.innerHTML = '' + avg;
}
function ResetFunc() {
total = 0;
count = 0;
avg = 0;
result.innerHTML = '0';
}
Well, for one, it should be inputVal.value (lowercase value). That should correctly pass the input value to your function. But your question doesn't really describe what issue you're running into, so I'm not sure that answers your question.
Also I don't think global is a valid keyword for JavaScript.
The problem is in this part onclick="AddFunc(inputVal.Value)". This will not pass value of inputVal to the function. You should store the <input> element in a variable and access its value using small vi.e value
var count = 0;
var total = 0;
var avg = 0;
var result = document.getElementById("average");
var input = document.getElementById('inputVal')
result.textContent = 0;
function AddFunc(e){
let value = Number(input.value);
total += value;
count += 1;
avg = total / count;
result.innerHTML = '' + avg;
}
function ResetFunc() {
total = 0;
count = 0;
avg = 0;
result.innerHTML = '0';
}
<input type="number" id="inputVal" placeholder="Input Value..."></number><br>
<button id="Btn_Avg" onclick="AddFunc(event)">Average</button>
<button id="Btn_Rst" onclick="ResetFunc()">Reset</button>
<p>Average: </p><p id="average">OK</p>

.innerHTML += id, no duplicates

Here what I have so I have a long list of check-boxes and I want to display them in text if they are check I was thinking of using the code below, but the problem I'm having is if they check and uncheck a check-box it shows up multiple times any suggestion on how to fix this?
.innerHTML += id;
If you need some more details here's a code dump of the relevant code:
Javascript
function findTotal() {
var items = new Array();
var itemCount = document.getElementsByClassName("items");
var total = 0;
var id = '';
for (var i = 0; i < itemCount.length; i++) {
id = "c" + (i + 1);
if (document.getElementById(id).checked) {
total = total + parseInt(document.getElementById(id).value);
document.getElementById(id).parentNode.classList.add("active");
document.getElementById(id).parentNode.classList.remove("hover");
document.getElementById('display').innerHTML += id;
} else {
document.getElementById(id).parentNode.classList.remove("active");
document.getElementById(id).parentNode.classList.add("hover");
}
}
console.log(total);
document.getElementById('displayTotal').value = total;
}
HTML
<label class="hover topping" for="c4">
<input class="items" onclick="findTotal()" type="checkbox" name="topping" value="1.00" id="c4">BABYBEL</label>
Note: many more label classes
Previous answer should do it. Here your code (see comment "clear container"
Additionally I have simplified your code a bit. Readability greatly increased.
Maybe you should switch to jQuery in general, much simpler for your example.
var displayElement = document.getElementById('display'),
displayTotalElement = document.getElementById('displayTotal');
function findTotal() {
var items = [],
itemCount = document.getElementsByClassName("items"),
total = 0,
id = '';
// clear container
displayElement.innerHTML = "";
for (var i = 0; i < itemCount.length; i++) {
id = "c" + (i + 1);
var element = document.getElementById(id),
elementsParent = element.parentNode;
if (element.checked) {
total = total + parseInt(element.value, 10);
elementsParent.classList.add("active");
elementsParent.classList.remove("hover");
displayElement.innerHTML += id;
} else {
elementsParent.classList.remove("active");
elementsParent.classList.add("hover");
}
}
console.log(total);
displayTotalElement.value = total;
}
Reset the text before the loop:
document.getElementById('display').innerHTML = '';
At the moment you're just always adding to whatever's already thereā€¦

Javascript: Read, Add and Display form values

I am trying to write a web app that takes user input as numbers in 15 text or number inputs on a html form, it should then add these values together and display the total in a label elsewhere on the page.
I have 15 inputs with the class name "takings" and a label with the ID "TotalLabel" on the page.
function getsum () {
var rows = document.getElementsByClassName("takings");
var total = 0;
for (var i = 0; i < rows.length; i++) {
var val = parseFloat(rows[i].value);
total += val;
}
var label = document.getElementById("TotalLabel");
label.value = total;
alert(parseFloat(total));
}
window.onload = getsum;
The alert is only in place for debugging purposes and it appears that the variable total is still set to zero at the end of the script. I also need to make the getsum() function fire every time a user enters data in any of the fields with class "takings".
Can anyone help?
So you need to add change events to all of the elements and call getsum
function getsum () {
var rows = document.getElementsByClassName("takings");
var total = 0;
for (var i = 0; i < rows.length; i++) {
var val = parseFloat(rows[i].value);
total += val;
}
var label = document.getElementById("TotalLabel");
label.value = total;
}
window.onload = getsum;
//Example showing how to add one event listener to the page and listen for change events
//The following works in modern browsers, not all browsers support addEventListener, target, and classList.
document.body.addEventListener("change", function(evt) {
var targ = evt.target;
if(targ.classList.contains("takings")) {
getsum();
}
});
label { display: block; }
<label>1</label><input type="text" class="takings" value="0"/>
<label>2</label><input type="text" class="takings" value="0"/>
<label>3</label><input type="text" class="takings" value="0"/>
<label>4</label><input type="text" class="takings" value="0"/>
<label>5</label><input type="text" class="takings" value="0"/>
<label>Total:</label><input type="text" id="TotalLabel" value="0" readonly/>
To have your getSum() function fire for all of those elements, you can use Javascript to add an onchange event to all elements with the required class name
var input = document.getElementsByClassName("takings");
for (var i = 0; i < cells.length; i++) {
input[i].onchange = getSum;
}
Other than that, I don't see any visible errors in your getSum() function.
You need to add an EventListener to your input fields and call getsum, for example
var a = document.getElementsByClassName("takings");
for (var i = 0;i<a.length;i++){
addEventListener('keyup',getsum);
}
Please note that a label has innerHTML, not a value:
label.innerHTML = total;
With your actual function, you will get NaN as a result as long as not all the inputs have a value, so you will need to add
if (val) {
total += val;
}
to your for loop.
Full working code:
function getsum(){
var rows = document.getElementsByClassName("takings");
var total = 0;
for (var i =0; i < rows.length; i++){
var val = parseFloat(rows[i].value);
if (val) {
console.log(val);
total += val;
}}
var label = document.getElementById("TotalLabel");
label.innerHTML = total;
}
var a = document.getElementsByClassName("takings");
for (var i = 0;i<a.length;i++){
this.addEventListener('keyup',getsum);
}
DEMO

Categories