Adding up inputs into an array and creating a sum - javascript

So my problem is I have multiple inputs that I'm trying to add up all the numbers from them up.
The values go into an array but I need to take that array and create the sum.
Also I have triggering the function onchange so that way the sum updates.
Here's currently what I have: https://codepen.io/DilionsCode/pen/vYGEXOm
var sum;
function Geeks() {
var input = document.getElementsByName("fields[]");
// ForLoop
input.forEach(Add);
}
function Add(item, index) {
var sum = sum + item;
}

You should not redeclare the variable sum inside the function and instead increment the global variable. Furthermore, you should be summing the values of the select elements.
function Add(item, index) {
sum = sum + Number(item.value);
}
Live Example:
var sum;
function Geeks() {
var input = document.getElementsByName("fields[]");
// ForLoop
sum = 0;
input.forEach(Add);
document.querySelector('#score').textContent = "Score: " + sum;
}
function Add(item, index) {
sum = sum + Number(item.value);
}
<select name="fields[]" onchange="Geeks()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="fields[]" onchange="Geeks()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<p id="score">Score: 2</p>

Updating the state of the global variable is not considered as the best practice.
function Geeks() {
var input = document.getElementsByName("fields[]");
let sum = 0;
// ForLoop
input.forEach((index, item) => {
sum = sum + Number(item.value);
});
}

Iterate with forEach through the input-fields and sum the values. parseInt is necessary because the values are strings.
function Geeks() {
let input = document.getElementsByName("fields[]");
let sum = 0;
input.forEach(elem => sum += parseInt(elem.value));
document.getElementById('score').innerHTML = 'Score: ' + sum;
}
// Initialize sum at start
Geeks();
<select name="fields[]" onchange="Geeks()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="fields[]" onchange="Geeks()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<p id="score">Score:</p>

Related

How can I get the id in a var in drawflow,js

I'm using a library call Drawflow
I have a select option here:
case 'email':
var template = `
<div>
Day(s) to Complete:
<select id="e_time" df-e_time>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
`;
editor.addNode('email', 1, 1, pos_x, pos_y, 'custom-node', {
"e_time": ""
}, template);
break;
I would like to use a loop to generate the option.
Here is my attempt:
case 'email':
var template = `
<div>
Day(s) to Complete:
<select id="e_time" df-e_time>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
<script>
window.onload = function() {testing()};
function testing() {
var elm = document.getElementById('e_time'),
df = document.createDocumentFragment();
for (var i = 1; i <= 42; i++) {
var option = document.createElement('option');
option.value = i;
option.appendChild(document.createTextNode("option #" + i));
df.appendChild(option);
}
elm.appendChild(df);
}
</script>
`;
editor.addNode('email', 1, 1, pos_x, pos_y, 'custom-node', {
"e_time": ""
}, template);
break;
if I put the loop inside the variable, then the program crash.
case 'email':
var template = `
<div>
Day(s) to Complete:
<select id="e_time" df-e_time>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
`;
editor.addNode('email', 1, 1, pos_x, pos_y, 'custom-node', {
"e_time": ""
}, template);
break;
<script>
window.onload = function() {testing()};
function testing() {
var elm = document.getElementById('e_time'),
df = document.createDocumentFragment();
for (var i = 1; i <= 42; i++) {
var option = document.createElement('option');
option.value = i;
option.appendChild(document.createTextNode("option #" + i));
df.appendChild(option);
}
elm.appendChild(df);
}
</script>
if I put the loop outside the switch statement, then the script doesn't run, I guess it's because it can't get the id.
I would like to ask what should I do?

JQuery add another value to each array item & sum

I currently have an array that is populated by changing the value/option of many select fields. E.g. If two select fields are in the dom and the options selected are 2 & 3 then the array would look like this - Array [ "2", "3" ]
Each select has a data attribute data-ticketprice which I would like to bind to each of the option values. So I can get the sum of both of the numbers e.g.
data attribute = 100
Select option value = 5
Sum = 100 x 5;
HTML -
<select class="ticket-qty" data-ticketprice="280.88" name="34">
<option value="0">0 Tickets</option>
<option value="1">1 Ticket</option>
<option value="2">2 Tickets</option>
<option value="3">3 Tickets</option>
<option value="4">4 Tickets</option>
<option value="5">5 Tickets</option>
</select>
<select class="ticket-qty" data-ticketprice="390" name="39">
<option value="0">0 Tickets</option>
<option value="1">1 Ticket</option>
<option value="2">2 Tickets</option>
<option value="3">3 Tickets</option>
<option value="4">4 Tickets</option>
<option value="5">5 Tickets</option>
</select>
Current jQuery -
//When select is changed update value to array
$('select.ticket-qty').on('change', function (e) {
//Map the values for the array
var arr = $('select.ticket-qty').map(function(){
return this.value
}).get()
//This sums the all the select options (not what I want)
var total = 0;
for (var i = 0; i < arr.length; i++) {
total += arr[i] << 0;
}
console.log(total);
});
You need to fill the array you build with map() with the selected quantity multiplied by the cost per item, which you can retrieve from the data attribute. From there you can use reduce() to sum up all values in the array. Something like this:
$('select.ticket-qty').on('change', function(e) {
var arr = $('select.ticket-qty').map(function() {
var cost = $(this).data('ticketprice');
var qty = $(this).val();
return cost * qty;
}).get();
var total = arr.reduce((a, b) => a + b, 0);
console.log(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="ticket-qty" data-ticketprice="280.88" name="34">
<option value="0">0 Tickets</option>
<option value="1">1 Ticket</option>
<option value="2">2 Tickets</option>
<option value="3">3 Tickets</option>
<option value="4">4 Tickets</option>
<option value="5">5 Tickets</option>
</select>
<select class="ticket-qty" data-ticketprice="390" name="39">
<option value="0">0 Tickets</option>
<option value="1">1 Ticket</option>
<option value="2">2 Tickets</option>
<option value="3">3 Tickets</option>
<option value="4">4 Tickets</option>
<option value="5">5 Tickets</option>
</select>
You should note that this can all be done in a single loop, however I am assuming you're building the array of individual totals for use elsewhere in your UI.
So how far I understand is, you want to multiply the selected value with the given data attribute on Select?
Here is sample code for getting Array of All selected values. And how to calculate the value you posted.
var array = [];
var i =0;
$('select.ticket-qty').on('change', function (e) {
// Get value of all selects in array.
$('select.ticket-qty').each(function(){
array[i] = $(this).val();
i++;
});
//calculate Sum ?
var data_attribute = $(this).data("ticketprice");
SelectedOptionValue = = $(this).val();
Sum = parseFloat(data_attribute)* parseInt(SelectedOptionValue);
});
Vanilla JS
const SELECTS = document.querySelectorAll('select.ticket-qty')
const LOG_SUM = e => {
const ticketPrice = e.target.getAttribute('data-ticketPrice')
const multiplier = e.target.value
const SUM = (+ticketPrice * +multiplier)
console.log(SUM)
}
SELECTS.forEach(select => {
select.addEventListener('change', e => {
LOG_SUM(e)
})
})
jQuery
$('select.ticket-qty').on('change', e => {
const ticketPrice = $(e.target).attr('data-ticketPrice')
const multiplier = e.target.value
const SUM = (+ticketPrice * +multiplier)
console.log(SUM)
});
Notice how i prepend the + operator to the ticketPrice & multiplier constants... this is because attr && value are returning Strings and the + operator converts numbers of type String into numbers of type Number
You can use some jQuery plugins to populate and reduce the select boxes.
(function($) {
$.reduce = function(arr, fn, initial) {
initial = typeof initial === 'undefined' ? 0 : initial;
$.each(arr, function(i, v) {
initial = fn(initial, v, i);
});
return initial;
};
$.fn.reduce = function(fn, initial) {
return $.reduce(this, fn, initial);
};
$.fn.populateCombo = function(opts) {
let data = opts.data || Array.apply(null, {length: opts.range || 0}).map(Number.call, Number);
return this.append(data.map(x => $('<option>')
.text(opts.textFn ? opts.textFn(x) : x)
.val(opts.valFn ? opts.valFn(x) : x)));
};
})(jQuery);
$('.ticket-qty').each((i, combo) => $(combo).populateCombo({
range : 6, textFn: v => v + ' Tickets'
}));
$('select.ticket-qty').on('change', function(e) {
var total = $('select.ticket-qty').reduce(function(result, item) {
return result + $(item).data('ticketprice') * $(item).val();
}, 0);
console.log('$' + total.toFixed(2));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="ticket-qty" data-ticketprice="280.88" name="34"></select>
<select class="ticket-qty" data-ticketprice="390" name="39"></select>

How to filter a list of options using a list of possible values

I'm looking to filter a list of options from a select input and remount the filtered list.
The backend will send over the array of options values that are to be filtered which match to those in the list.
I'm not sure if options is the best attribute to use? (
var initial_options = $('select_id').options
The options are of the form eg
[
'<option value="" selected="">Option 0</option>',
'<option value="1">Option 1</option>'],
...
]
the returned data to be used for filtering is of the form
var option_values_filter = [1,3,5,6]
then mounted with:
$('#select_id').html(filtered_options)
Assuming that your values filter is attempting to filter on the actual value option property you can try something like this:
const option_values_filter = [1, 3, 4];
const filtered = $("#id option").filter((index, option) => {
return (option_values_filter.indexOf(parseInt(option.value)) !== -1);
});
$(id).html(filtered);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="id">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
Here is a pure javascript solution:
const option_values_filter = [1, 3, 4];
const selectElement = document.getElementById("id");
const newOptions = Array.apply(null, selectElement.options).filter((option) => {
return option_values_filter.indexOf(parseInt(option.value)) !== -1;
}).map(option => option.outerHTML);
selectElement.innerHTML = newOptions;
<select id="id">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
This is an answer in combination with your last question. Using pure javascript.
var selectBoxEl = document.getElementById('selectBox');
var arrayOfNodes = selectBoxEl.childNodes;
var optionsArr = [];
var filteredArr = [];
var option_values_filter = [1, 3, 5, 6]
// loop through child nodes of select box and store option nodes as a string in array
for (var i = 0; i < arrayOfNodes.length; i++) {
if (arrayOfNodes[i].nodeName === 'OPTION') {
optionsArr.push(arrayOfNodes[i].outerHTML);
}
}
// function to filter options array and set select box options to filtered array
function filterOptions(filterOps) {
console.log(optionsArr[0].indexOf('value="'));
var val;
for (var i = 0; i < optionsArr.length; i++) {
val = optionsArr[i].substring(optionsArr[i].indexOf('value="') + 7, optionsArr[i].indexOf('value="') + 8);
if (filterOps.indexOf(parseInt(val)) !== -1) {
filteredArr.push(optionsArr[i]);
}
}
selectBoxEl.innerHTML = filteredArr;
}
filterOptions(option_values_filter);
<select id="selectBox">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>

select.getElementsByTagName except for a certain option

Option List
I have an problem where my Random Option Picker picks a certain option that I don't want. How do I mitigate this?
var select = document.getElementById('edit-categories');
var items = select.getElementsByTagName('option');
var index = Math.floor(Math.random() * items.length + 1);
return select.selectedIndex = index;
The option that I want my random picker to ommit is : value="_none"
Use querySelectorAll along with :not and an attribute selector:
var items = select.querySelectorAll('option:not([value="_none"])');
var select = document.querySelector('select');
var items = select.querySelectorAll('option:not([value="_none"])');
console.log(items);
<select>
<option value="_none">--</option>
<option value="water">Water</option>
<option value="waste">Waste</option>
</select>
As an alternative, you can also use Array.prototype.filter (since It's a lot easier to pollyfil filter than the [not] selector):
var opts = [].filter.call(document.getElementById('edit-categories').options, function(opt){return opt.value != '_none'})
console.log(opts);
<select id="edit-categories">
<option value="_none">None
<option value="foo">Foo
<option value="foo">Bar
</select>
You can add a while loop just before setting the index :
var select = document.getElementById('edit-categories');
var items = select.getElementsByTagName('option');
var index = Math.floor(Math.random() * items.length);
while (items[index].value == '_none') {
index = Math.floor(Math.random() * items.length);
}
select.selectedIndex = index;
<select id="edit-categories">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="_none">none</option>
<option value="4">4</option>
</select>

Need Value from Simple Javascript Addition Multiplication

I'm not sure what I am doing wrong, but I am just trying to get a total price to display after you make a selection. I want to take the value of the selection and multiply it by 100 and then use the updatetotal function to display the total.
// Collect Data & Prices To Update Dynamic Prices
var pricechecking=document.getElementById('howmanyaccts')value.trim();
var pricepaypal=document.getElementById('howmanyacctspaypal')value.trim();
var pricecheck = pricechecking * 100;
var pricepay = pricepaypal * 100;
function updateTotal() {
var ThePrice = pricecheck + pricepay;
$('#TotalPrice').text('$' + ThePrice + '.00');
}
$(function () { $('.DoPricing').click(updateTotal); });
MY HTML IS:
<form action="http://linktomyactionpage" method="post" >
<p>How many accounts to pay by check?</p>
<select name="howmanyaccts" id="howmanyaccts" class="DoPricing">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<p>How many accounts to pay by paypal?</p>
<select name="howmanyacctspaypal" id="howmanyacctspaypal" class="DoPricing">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<p>Total: <span id="TotalPrice">$0.00</span></p>
<input type="submit" name="submit" value="submit">
</form>
What if I simplified the code? Brought the 00.00 to the text and no multiplication?
// Collect Data & Prices To Update Dynamic Prices
var pricechecking=document.getElementById('howmanyaccts').value.trim();
var pricepaypal=document.getElementById('howmanyacctspaypal').value.trim();
function updateTotal() {
var ThePrice = pricechecking + pricepaypal;
$('#TotalPrice').text('$' + ThePrice + '00.00');
}
$(function () { $('.DoPricing').click(updateTotal); });
HERE IS WHAT I GOT TO WORK:
// Collect Data & Prices To Update Dynamic Prices
var pricechecking=document.getElementById('howmanyaccts').value.trim();
var pricepaypal=document.getElementById('howmanyacctspaypal').value.trim();
function updateTotal() {
var pricecheck = parseInt($('#howmanyaccts').val(), 10);
var pricepay = parseInt($('#howmanyacctspaypal').val(), 10);
var ThePrice = pricecheck + pricepay;
$('#TotalPrice').text('$' + ThePrice + '00.00');
}
$(function () { $('.DoPricing').click(updateTotal); });
I think you want to do something like this : http://jsfiddle.net/F3HbJ/
$(function () {
$('.DoPricing').change(function () {
var total = 0;
$('.DoPricing').each(function () {
total += parseInt($(this).val()) * 100;
});
$('#TotalPrice').html('$' + total);
});
});
The event handler is .change() for a select. Then you loop through the parseInt values of each select that you multiply by 100.
Here is working DEMO
use like this :
$(document).ready(function () {
var pricechecking = $($("#howmanyaccts")[0].selectedOptions).attr("value");
var pricepaypal = $($("#howmanyacctspaypal")[0].selectedOptions).attr("value");
function updateTotal() {
var pricecheck = parseInt($('#howmanyaccts').val(), 10);
var pricepay = parseInt($('#howmanyacctspaypal').val(), 10);
var ThePrice = pricecheck + pricepay;
$('#TotalPrice').text('$' + ThePrice + '00.00');
}
$('.DoPricing').change(updateTotal);
});

Categories