Need Value from Simple Javascript Addition Multiplication - javascript

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);
});

Related

Issue with event listener and value not updating

I am having an issue with an event listener on a select and a value not updating but cannot figure out what the issue.
Code is below. Basically need the price field to update based on the function above it. Unfortunately i cannot have them all in the same function and need to have them separate. The first console.log does show the value for y but the second does not show the value for price.
var factors = function factor(j) {
var mySelect = document.getElementById("mySelect").value;
if (mySelect == "car") {
lease = "166";
} else if (mySelect == "truck") {
lease = "200";
}
console.log("this is my lease value - " + lease);
return lease * j;
};
var monthlyprice = function monthlyprice() {
var price = factors(1);
console.log("this is my price -" + price);
};
var type = document.getElementById("mySelect");
type.addEventListener("click", factors);
<form action="">
<label for="mySelect">Shipment Type</label>
<select id="mySelect">
<option value="car">Car</option>
<option value="truck">Truck</option>
</select>
</form>
since monthlyprice calls factor() you want to place the listener on monthlyprice
var type = document.getElementById("mySelect");
type.addEventListener("change", monthlyprice);
function monthlyprice() {
var price = factor(1)
console.log("this is my price =" + price);
};
function factor(j) {
var y;
var z = document.getElementById("mySelect").value;
if (z == "car") {
y = "166";
} else if (z == "truck") {
y = "200";
}
console.log("this is my y value - " + y);
return y * j;
};
<form action="">
<label id="label">Shipment Type</label>
<select id="mySelect">
<option value="car">Car</option>
<option value="truck">Truck</option>
</select>
</form>

Adding up inputs into an array and creating a sum

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>

Drop down menu adds input fields with corresponding ID and label

With Javascript, I created a drop down menu that generates the number of input fields that the user's selection (1-6) dictates. But how do I make the newly generated input fields' IDs & labels correspond to their place-number in the list of input fields? I hope that makes sense. You'll see in my html I have [ brackets ] where I want the dynamically generated number to be.
html:
<ul>
<li>
<label for="id_NOU">Number of Units:</label>
<select name="NOU" id="id_NOA">
<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>
<option value="6">6</option>
</select>
</li>
<li class="list">
<label>Unit []</label>
<input type="text" id="unit[]"></input>
</li>
</ul>
JavaScript:
$(window).load(function () {
$('#id_NOU').change(function () {
var total = $(this).val();
//remove all
$('.list').each(function (index) {
if (index != 0) $(this).remove();
});
//create new ones
for (var i = 2; i <= total; i++) {
$('.list:first').clone().appendTo('ul');
}
});
});
Thank you so much for your help! I love JSFiddles...
Perhaps a better implementation would be to copy last field only and on further change keep the rest of the list intact
here is the code
var counter = 1;
$(function(){
$("#id_NOA").on("change", function(){
var $ul = $(this).parent().parent();
var val = $(this).val();
while($ul.find(".list").length < val){
var $item = $ul.find(".list:last").clone();
$item.find("input").attr("id", "unit"+counter++);
$item.find("label").html("Unit "+counter);
$ul.append($item);
}
if($ul.find(".list").length >= val){
$ul.find(".list:gt("+(val-1)+")").remove();
counter = val;
}
});
});
here is a jsfiddle link http://jsfiddle.net/EN687/1/
Solution:
$(document).ready(function(){
$('#id_NOU').change(function () {
var total = $(this).val();
//remove all
$('.list').each(function (index) {
if (index != 0) $(this).remove();
});
//create new ones
for (var i = 2; i <= total; i++) {
element = $('.list:first').clone();
element.find('input').attr('id', 'unit' + i);
element.find('label').html('Unit ' + i);
element.appendTo('ul');
}
});
});
Working demo: http://jsfiddle.net/6VQDR/1/

Calculate tax rate with selects using javascript

I've been using code from this question to create something very similar, the only thing I want to change is the calculation to get a different total result.
In that example they take the first value times the other and then echo out the result.
Taking the first value times the second works very well, but when I try to make the calculation more advanced it all fails.
I want to be able to make the following equation with the selected values:
var total = ((firstSelect*secondSelect)-firstSelect*0,68)*300;
alert(total);
I've also tried the following and this too fails:
var oppa = firstSelect * rate;
var gagnam = secondSelect * 0.68;
var style = oppa - gagnam;
var total = style * 300;
alert(total);
Currently my HTML looks like this:
<p>Number of sales</p>
<select name="firstSelect" id="firstSelect" class="DoPricing">
<option value="15">15</option>
<option value="20">20</option>
<option value="25">25</option>
<option value="30">30</option>
<option value="35">35</option>
<option value="40">40</option>
<option value="45">45</option>
<option value="50">50</option>
<option value="55">55</option>
<option value="100">100</option>
<option value="150">150</option>
</select>
<p>Times rate</p>
<select name="secondSelect" id="secondSelect" class="DoPricing">
<option value="0.99">0.99</option>
<option value="1.15">1.15</option>
<option value="1.5">1.5</option>
<option value="2">2</option>
<option value="2.5">2.5</option>
<option value="3">3</option>
</select>
<br>
<br>
<input type="submit" name="submit" value="submit" id="submit">
and my JS
function calc() {
var total,
nSales,
rate;
var nSales = document.getElementsByName("firstSelect")[0].value;
var rate = document.getElementsByName("secondSelect")[0].value;
var oppa = nSales * rate;
var gagnam = rate * 0.68;
var style = oppa - gagnam;
var total = style * 300;
alert(total);
}
window.onload = function () {
document.getElementById("submit").onclick = calc;
};
How would I go about to accomplish this?
You have the onclick handler inside the calc() function, you should have it outside so it add the event listener on windows.onload
function calc() {
var total,
nSales,
rate;
var nSales = document.getElementsByName("firstSelect")[0].value;
var rate = document.getElementsByName("secondSelect")[0].value;
var oppa = nSales * rate;
var gagnam = nSales* 0.68; //changed to nSales
var style = oppa - gagnam;
var total = style * 300;
alert(total);
};
window.onload = function () {
document.getElementById("submit").onclick = calc;
}
Demo here

Use HTML dropdown list values with JavaScript

This is what I'm trying to do:
The user selects either option "One" or option "Two".
If the user select "One" the result is 66 + 45 or if the user select "Two" the result is 35 + 45.
How can I implement this using HTML and JavaScript?
This is what I've done so far:
HTML:
<select id="number">
<option>One</option>
<option>Two</option>
</select>
...
// Result
<div id="result"></div>
JAVASCRIPT:
function test(eventInfo) {
var userSelection = document.getElementById("number").value;
if () {
result = 66 + 45;
} else {
result = 35 + 45;
}
var greetingString = userSelection;
document.getElementById("result").innerText = greetingString;
}
Consider:
<select id="number">
<option value="66">One</option>
<option value="35">Two</option>
</select>
then:
result = 45 + +document.getElementById("number").value;
How about this. Set the values in data-attribute and calculate the sum.
<select id="number">
<option value="1" data-Values="66,45">One</option>
<option value="2" data-Values="35,28">Two</option>
</select>
<div id="result"></div>
JS
var values = this.options[this.selectedIndex].getAttribute('data-Values');
var sum = eval(values.split(',').join('+')); //Use with caution eval.
document.getElementById("result").innerHtml = sum;
Demo
Why don't you use value:
<select id="number">
<option value="66+45">One</option>
<option value="35+45">Two</option>
</select>
var greetingString = $("#number option:selected").val();
// or document.getElementById("number").value;
document.getElementById("result").innerText = greetingString;
Use Switch Statement:
Html:
<select id="number">
<option value="66">One</option>
<option value="35">Two</option>
</select>
Javascript:
var userSelection = document.getElementById("number").value;
switch (userSelection)
{
case 66:
result = 66 + 45;
break;
case 35:
result = 35 + 45;
break;
}
You can try this one:
<select id="number" onchange="test(this.value);">
<option value="66+45">One</option>
<option value="35+45">Two</option>
</select>
...
// Result
<div id="result">here</div>
JS
<script>
function test(val) {
document.getElementById("result").innerHtml = val;
}
</script>

Categories