On input change, get all input values in div and update label - javascript

I have the following HTML:
<div class="filters">
<div class="filter-label">6</div>
<div class="filter-inputs">
<input type="number" name="i1" id="i1" value="1" min="0" step="1" />
<input type="number" name="i2" id="i2" value="2" min="0" step="1" />
<input type="number" name="i3" id="i3" value="3" min="0" step="1" />
</div>
</div>
The question:
I'd like to, when any input is changed, I want to get that value and
the value of the other two text boxes and add them all together. Once
I have the total value, I need to then change the text of the label
with the new value.
I also have the following JavaScript (jQuery) to detect when a change has happened, but after that, I can't figure out how to loop through each input in the div and get the value.
$('.filter .filter-inputs input').on('input', function() {
var element = $(this);
// ...
});
I looked at loops like the jQuery each method but I've got no idea how to loop through each input inside the filter-inputs div.

You could create array from inputs using map and get methods and then calculate sum with reduce method.
let inputs = $('.filters input');
let label = $('.filter-label');
inputs.on('input', function() {
let sum = inputs.map(function() {
return $(this).val()
}).get().reduce((r, e) => r + +e, 0);
label.text(sum)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="filters">
<div class="filter-label">6</div>
<div class="filter-inputs">
<input type="number" name="i1" id="i1" value="1" min="0" step="1" />
<input type="number" name="i2" id="i2" value="2" min="0" step="1" />
<input type="number" name="i3" id="i3" value="3" min="0" step="1" />
</div>
</div>
Or you could just create array with Array.from method and then use reduce method to sum values.
let inputs = $('.filters input');
let label = $('.filter-label');
inputs.on('input', function() {
label.text(Array.from(inputs).reduce((r, {value}) => r + +value, 0))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="filters">
<div class="filter-label">6</div>
<div class="filter-inputs">
<input type="number" name="i1" id="i1" value="1" min="0" step="1" />
<input type="number" name="i2" id="i2" value="2" min="0" step="1" />
<input type="number" name="i3" id="i3" value="3" min="0" step="1" />
</div>
</div>

Use this script
$('.filter-inputs input').change(function(){
var total = 0;
$('.filter-inputs input').each(function(){
total += parseInt($(this).val());
});
$('.filter-label').html(total);
});

No problem!
$('.filter .filter-inputs input').on('input', function() {
//not needed:
//var element = $(this);
// Obtain numeric entries
var i1 = Number($("#i1").val());
var i2 = Number($("#i2").val());
var i3 = Number($("#i3").val());
// Calculate sum of entries
var total = i1 + i2 + i3;
// Populate label div with sum
$(".filter-label").html(String(total));
});
Good luck!

You don't need jQuery for this task http://jsfiddle.net/72e3jLc0/
let label = document.querySelector('.filter-label');
let inputs = document.querySelectorAll('.filter-inputs input');
inputs.forEach(input => {
input.addEventListener('change', e => {
label.innerText = parseInt(label.innerText) + parseInt(input.value);
});
});

Try using the following approach:
$(document).ready(function() {
var total=0;
$("input[type='number']").change(function() {
$(".results").html("");
var objects = $(".filters").find("input[type='number']");
for (var i = 0; i < objects.length; i++) {
total += parseInt($(objects[i]).val());
}
$(".filter-label").text(total);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="filters">
<div class="filter-label">6</div>
<div class="filter-inputs">
<input type="number" name="i1" id="i1" value="1" min="0" step="1" />
<input type="number" name="i2" id="i2" value="2" min="0" step="1" />
<input type="number" name="i3" id="i3" value="3" min="0" step="1" />
</div>
</div>

I know this is an old thread, but I would like to give my contribution.
The id can be replaced with document or "body", and input is not necessary if all your inputs have the class .form-control.
$("#id-of-overall-div-element").on("change", "input, .form-control", function () {
// Do something
});

Related

create dropdown with multiple selection in JS

I want to implement a dropdown similar to the one on Booking.com in terms of functionality (I attach a screenshot), but I am encountering some issues and I can't figure out where I'm going wrong. Do you have any suggestions?
HTML
<div class="dropdown">
<input type="text" id="droptxt" class="list" readonly placeholder="Number of guests">
<div id="content" class="content">
<div class="list">
<input type="checkbox" id="rooms" class="list" value="Choose how many rooms" />
<label for="Choose how many rooms" class="list">Choose how many rooms </label>
<input type="hidden" class="list quantity" min="1" value="1" />
</div>
<div class="list">
<input type="checkbox" id="adults" class="list" value="Choose the number of adults" />
<label for="Choose the number of adults" class="list">Choose the number of adults </label>
<input type="hidden" class="list quantity" min="1" value="1" />
</div>
<div class="list">
<input type="checkbox" id="children" class="list" value="Choose the number of children" />
<label for="Choose the number of children" class="list">Choose the number of children </label>
<input type="hidden" class="list quantity" min="1" value="1" />
</div>
</div>
</div>
JavaScript
const txt = document.getElementById('droptxt');
console.log(txt);
const content = document.getElementById('content');
console.log(content);
const checkboxes = document.querySelectorAll('.list input[type="checkbox"]');
const quantity = document.querySelectorAll('.list input[type="number"]');
txt.addEventListener('click', function() {
content.classList.toggle('show');
});
// Close the dropdown if the user clicks outside of it
window.onclick = function(e) {
if (!e.target.matches('.list')) {
if (content.classList.contains('show')) content.classList.remove('show');
}
};
checkboxes.forEach(function(checkbox, index) {
checkbox.addEventListener('click', function() {
quantity[index].type = (checkbox.checked) ? 'number' : 'hidden';
calc();
});
});
quantity.forEach(function(input) {
input.addEventListener('input', calc);
});
function calc() {
let arr = [];
for (let i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
arr.push(quantity[i].value + ' x ' + checkboxes[i].value);
}
}
txt.value = arr.join(', ');
}
const quantity = document.querySelectorAll('.list input[type="number"]');
in this line you are selecting input[type="number"] but in your html there is no input which type is number. use this
const quantity = document.querySelectorAll('.list input[type="hidden"]');
it will solve your problem

Insert Input Value into Label Text Javascript

I have 3 range inputs:
When the user starts to drag the range thumb, I'd love the of related input value to be printed in the label before main text. For this I wrote a funtion, but nothng works
let rangeForm = document.querySelectorAll('.form-range');
let rangeValue = document.querySelectorAll('.input-value');
window.onload = () => {
rangeForm.forEach((input) => input.value = '0');
}
function findTotal() {
var tot = 0;
rangeForm.forEach((input) => tot += parseInt(input.value, 10));
document.getElementById('total-cost').innerHTML = tot;
}
function changeLabel() {
rangeValue.forEach((label) => label.inhherHTML = `${parseInt(input.value, 10)}`);
}
<label for="storiesNumber" class="form-label"><p class="input-value"></p>some text</label>
<input type="range" oninput="findTotal();changeLabel()" class="form-range" min="0" max="100" id="storiesNumber">
<label for="postsNumber" class="form-label"><p class="input-value"></p>another text</label>
<input type="range" oninput="findTotal();changeLabel()" class="form-range" min="0" max="100" id="postsNumber">
<label for="reelsNumber" class="form-label"><p class="input-value"></p>more text</label>
<input type="range" oninput="findTotal();changeLabel()" class="form-range" min="0" max="100" id="reelsNumber">
Check out this snippet, I guess it fits your purpose:
let rangeForm = document.querySelectorAll('.form-range');
let rangeValue = document.querySelectorAll('.input-value');
window.onload = () => {
rangeForm.forEach((input) => input.value = '0');
}
function findTotal() {
var tot = 0;
rangeForm.forEach((input) => tot += parseInt(input.value, 10));
document.getElementById('total-cost').innerHTML = tot;
}
function changeLabel(input) {
document.querySelector("label[for="+input.id+"] > .input-value").innerText = `${parseInt(input.value, 10)}`
}
<label for="storiesNumber" class="form-label">
some text: <b class="input-value"></b>
</label>
<input type="range" oninput="findTotal();changeLabel(this)" class="form-range" min="0" max="100" id="storiesNumber">
<br>
<label for="postsNumber" class="form-label">
another text: <b class="input-value"></b>
</label>
<input type="range" oninput="findTotal();changeLabel(this)" class="form-range" min="0" max="100" id="postsNumber">
<br>
<label for="reelsNumber" class="form-label">
more text: <b class="input-value"></b>
</label>
<input type="range" oninput="findTotal();changeLabel(this)" class="form-range" min="0" max="100" id="reelsNumber">
<br>
Total: <b id="total-cost">...</b>

jQuery/Javascript complex iterate over elements

We have a form and need to iterate over some elements to get the final sum to put in a "total" element.
E.g., here is a working starter script. It doesn't NOT iterate over the other ones. It does NOT consider the elements "item*", below, yet but should. Keep reading.
<script>
$( document ).ready(function() {
$('#taxsptotal').keyup(calcgrand);
$('#shiptotal').keyup(calcgrand);
$('#disctotal').keyup(calcgrand);
function calcgrand() {
var grandtot = parseFloat($('#subtotal').val(), 10)
+ parseFloat($("#taxsptotal").val(), 10)
+ parseFloat($("#shiptotal").val(), 10)
- parseFloat($("#disctotal").val(), 10)
$('#ordertotal').val(grandtot);
}
});
</script>
We are adding more to this. Think of having many items in a cart and each one has the same elements for the following where "i" is a number designating an individual item.
<!-- ordertotal = sum of #subtotal, #taxptotal, #shiptotal and #disctotal -->
<input type="text" id="ordertotal" name="ordertotal" value="106.49">
<input type="text" id="taxsptotal" name="taxsptotal" value="6.72">
<input type="text" id="shiptotal" name="shiptotal" value="15.83">
<input type="text" id="disctotal" name="disctotal" value="0.00">
<!-- sum of the cart "itemtotal[i]" -->
<input type="text" id="subtotal" name="subtotal" value="83.94">
<!-- cart items
User can change any itemprice[i] and/or itemquantity[i]
itemtotal[i] = sum(itemquantity[i] * itemprice[i])
-->
<input type="text" name="itemtotal[1]" value="8.97" />
<input type="text" name="itemquantity[1]" value="3" />
<input type="text" name="itemprice[1]" value="2.99" />
<input type="text" name="itemtotal[2]" value="4.59" />
<input type="text" name="itemquantity[2]" value="1" />
<input type="text" name="itemprice[2]" value="4.59" />
<input type="text" name="itemtotal[3]" value="0.99" />
<input type="text" name="itemquantity[3]" value="10" />
<input type="text" name="itemprice[3]" value="9.90" />
(1) User can change any itemprice[i] and/or itemquantity[i], so each needs a keyup. I can do that in php as it iterates over the items.
(2) These elements will have a $('.itemtotal[i]').keyup(calcgrand); (Or function other than calcgrand, if needed) statement, too. That keyup can be added by the php code as it evaluates the items in the cart.
(3) When an element is changed, then the script should automatically (a) calculate the $('[name="itemtotal[i]"]').val() and (b) replace the value for $('[name="itemtotal[i]"]').val().
(4) Then, the script above will use the $('[name="itemtotal[i]"]').val() to (a) replace the #subtotal value and (b) use that value in the equation.
Can someone help me with this? I am stuck on how to iterate over the [i] elements.
p.s. Any corrections/enhancements to the above code is appreciated, too.
Add a custom class to the desired inputs to sum:
HTML:
<input type="text" class="customclass" name=itemtotal[1] value="8.97" />
<input type="text" class="customclass" name=itemquantity[1] value="3" />
<input type="text" class="customclass" name=itemprice[1] value="2.99" />
JS:
var sum = 0;
$.each('.customclass',function(i, item){
sum = sum + Number($(this).val());
})
alert(sum);
if you for example group your inputs by giving them a class, or have each group in a div like so:
<!-- ordertotal = sum of #subtotal, #taxptotal, #shiptotal and #disctotal -->
<input type="text" id="ordertotal" name="ordertotal" value="106.49">
<input type="text" id="taxsptotal" name="taxsptotal" value="6.72">
<input type="text" id="shiptotal" name="shiptotal" value="15.83">
<input type="text" id="disctotal" name="disctotal" value="0.00">
<!-- sum of the cart "itemtotal[i]" -->
<input type="text" id="subtotal" name="subtotal" value="83.94">
<!-- cart items
User can change any itemprice[i] and/or itemquantity[i]
itemtotal[i] = sum(itemquantity[i] * itemprice[i])
-->
<div class="group">
<input type="text" name="itemtotal[1]" value="8.97" />
<input type="text" name="itemquantity[1]" value="3" />
<input type="text" name="itemprice[1]" value="2.99" />
</div>
<div class="group">
<input type="text" name="itemtotal[2]" value="4.59" />
<input type="text" name="itemquantity[2]" value="1" />
<input type="text" name="itemprice[2]" value="4.59" />
</div>
<div class="group">
<input type="text" name="itemtotal[3]" value="0.99" />
<input type="text" name="itemquantity[3]" value="10" />
<input type="text" name="itemprice[3]" value="9.90" />
</div>
Then you could do the following in javascript:
function calcSubTotal() {
$('[name^="itemtotal"]').each(function(i){
var sum = 0;
$('[name^="itemtotal"]').each(function(i){
sum += $(this).val();
});
$('#subtotal').val(sum);
});
}
$('.group').each(function(i) {
var total = $(this).find('[name^="itemtotal"]');
var qnt = $(this).find('[name^="itemquantity"]');
var price = $(this).find('[name^="itemprice"]');
total.keyup(function(e){
price.val(total.val() * qnt.val());
calcSubTotal();
});
qnt.keyup(function(e){
price.val(total.val() * qnt.val());
calcSubTotal();
});
});
$("[name^='itemprice'], [name^='itemquantity']").keyup(function(){
var input_name = $(this).attr('name');
var temp_name_split = input_name.split(/[\[\]]+/);
var temp_total = parseInt($('[name="itemquantity['+temp_name_split[1] +']"]').val()) * parseFloat($('[name="itemprice['+temp_name_split[1] +']"]').val());
$('[name="itemtotal['+temp_name_split[1]+']"]').val(temp_total.toFixed(2));
var total = 0;
$("[name^='itemtotal']").each(function() {
total += parseFloat($(this).val());
});
$('#subtotal').val(total.toFixed(2));
});

Getting the average value of multiple input-type range sliders

I have a div with 5 input-type range silders and a submit button.
<div class="sliders" id="sliderbox">
<input type="range" name="points" min="0" max="100">
<input type="range" name="points1" min="0" max="100">
<input type="range" name="points2" min="0" max="100">
<input type="range" name="points3" min="0" max="100">
<input type="range" name="points4" min="0" max="100">
<input type="submit">
</div>
Under this div, I have four other hidden divs that contain content.
<div id="hidden1">Content</div>
<div id="hidden2">Content</div>
<div id="hidden3">Content</div>
<div id="hidden4">Content</div>
How can I get the average combined value (a number between 0 & 100) of all the rangesliders, and then slidetoggle one of these hidden divs on submit?
For example, if the cumulative average value of these sliders is between 0 to 25 on submit, is it possible for me to display "hidden1"? Or if the value is between 25 to 50, "hidden2" and so on?
So you have 5 sliders all having the same MAX value of 100. So max 500
To get Element index from the current range value:
Floor(current * endMax / (startMax + 1))
Example
const $sliders = $("#sliderbox").find("input[type='range']");
const $cont = $(".cont");
const totSliders = $sliders.length; // 5
const startMax = totSliders * parseInt($sliders.prop("max"), 10); // 500
const endMax = $cont.length; // 4
$sliders.on("input", function() {
// Get accumulated value of 5 sliders: 0...500
const current = $sliders.get().reduce((ac, el) => ac + parseInt(el.value, 10), 0);
// Get index 0...3
const index = Math.floor(current * endMax / (startMax + 1));
$cont.addClass("hide").eq( index ).removeClass("hide");
console.clear(); console.log('Current:' + current + ' Index:'+ index);
}).trigger("input"); // To make immediate effect
.hide {
display: none;
}
<div class="sliders" id="sliderbox">
<input type="range" name="points" min="0" max="100" value="0">
<input type="range" name="points1" min="0" max="100" value="0">
<input type="range" name="points2" min="0" max="100" value="0">
<input type="range" name="points3" min="0" max="100" value="0">
<input type="range" name="points4" min="0" max="100" value="0">
</div>
<div class="cont hide" id="hidden1">1 Content</div>
<div class="cont hide" id="hidden2">2 Content!!!</div>
<div class="cont hide" id="hidden3">3 Content</div>
<div class="cont hide" id="hidden4">4 Content!!!</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here I put in place some javascript. Probably this is something you want.
let avg = 0;
document.querySelector('.submit').addEventListener('click', event => {
document.querySelectorAll('.range').forEach(item => {
avg = Number(item.value) + avg;
});
avg = avg / 5;
if (avg >= 0 && avg <= 25) {
avg = 0;
document.querySelector('#hidden1').classList.add('show');
document.querySelector('#hidden1').classList.remove('hide');
}
});
JSFiddle
Using plain Javascript: if you utilize [HTMLNode].children, this will give you an array of elements within that node.
So you can gather all your inputs with:
document.getElementById('sliderbox').children
This will give you an HTMLCollection, that you can then iterate through with a for loop to retrieve each item's value, and calculate the average from that.

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"/>

Categories