Jquery multiply and add span and dropdown values - javascript

I am trying to compute the total price of items in a cart in Javascript. This is by multiplying the quantity by the unit price and then getting the grand total.
The cart is populated by a PHP while loop so I am using class names.
The quantity field is a dropdown/select and the price field is a span.
function sum() {
var sum = 0;
var q = 0;
var s = 0;
$('.itPrice,.qtys').each(function() {
q = $('.qtys').text() || 0; //quantity
s = $('.itPrice').text() || 0; //unit price
sum = sum + (q * s);
});
//display total
$("#sumT").text(sum);
}
<!-- inside PHP while loop -->
<label>Price: </label>
<span class="itPrice"><b>'.$row["price"].'</b></span>
<label>Quantity: </label>
<Select id="qty" name="qty" class="qtys">
<option value="1" selected>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>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</Select>
<span id="sumT" name="sumT">*sum goes here*</span>
The output is NaN (Not a Number). Where am I going wrong? There is also a problem with the HTML select, it's not picking the selected option, only working with option '1'.

You can select both related elements, as two collections of object, an iterate one collection (while using the array index to refer to the other); that way you can get the quantity and the price.
To get a select selected element, use jquery val() function instead of text();
As a side note, you should not use duplicate id's or names for inputs in yout html. If you want an input with the same name, you can use qty[] for example.
function sum() {
var sum = 0, // Total sum
it = $('.itPrice'), // All the .itPrice elements
qty = $('.qtys'); // All the .qtys elements
// For each .itPrice element
it.each(function(i, e) {
var current = $(this), // Gets the current .itPrice element
related = $(qty[i]); // Get the related .qtys element, by array index
// Sum
sum += Number(current.find('b').text()) * related.val();
});
// return total
return sum;
}
$('#calc').click(function() {
console.log(sum());
});
console.log(sum());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Price: </label>
<span class="itPrice"><b>100</b></span>
<label>Quantity: </label>
<Select id="qty" name="qty" class="qtys">
<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>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</Select>
<br>
<br>
<label>Price: </label>
<span class="itPrice"><b>200</b></span>
<label>Quantity: </label>
<Select id="qty" name="qty" class="qtys">
<option value="1" selected>1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4" selected>4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</Select>
<br>
<br>
<a id="calc" href="javascript:;">Get total</a>

Related

The function is not running well while using a global variable

I am trying to make a probability finder to take some random numbers and find the probability of a number from the array of random numbers. I have the following code :
/*********************Select Random Number**********************/
//Number of cases
var nOC = document.getElementById("noc").value;
function rollDice() {
//Number of trials
let nOT = document.getElementById("not").value;
//Empty Array to be filled
let array = [];
//Loop which pushes random numbers in the empty array
for (let i = 1; i <= nOT; i++) {
array.push(Math.ceil(Math.random() * nOC));
}
//Display results in a paragraph
document.getElementById("para").innerHTML = "Your random numbers are " + array;
}
/*********************Get Probability**************************/
function getProbabilityOf() {
//Probability of...
let oP = document.getElementById("op").value;
//Check if the number is out of range. If no, then find the probability of given number
if (oP >= noC) {
alert("This number is out of the range of possible outcomes that you have selected in step 1");
} else {
//Some code here
}
}
<!---------------------------Intro------------------------------>
<h1>Probability Finder</h1>
<hr/>
<p>With our probability finder, you can easily choose the number of possible cases and select the number of times you want to select a random case each time from the total cases and finally find the empirical probability of and case you want from the selected
total number of cases.</p>
<!---------------------------Step 1------------------------------>
<h3><span class="bold">Step 1 :</span>Select total number of cases:</h3>
<select id="noc">
<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>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<!---------------------------Step 2---------------------------->
<h3><span class="bold">Step 2 :</span>Select total number of trials</h3>
<select id="not">
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="50">50</option>
<option value="60">60</option>
<option value="70">70</option>
<option value="80">80</option>
<option value="90">90</option>
<option value="100">100</option>
</select>
<!----------------------------Step 3----------------------------->
<h3><span class="bold">Step 3 :</span>Get random numbers by experiment</h3>
<button onclick="rollDice()">Get random numbers</button>
<p id="para"></p>
<!----------------------------Step 4----------------------------->
<h3><span class="bold">Step 4 :</span>Get probability of a particular number</h3>
<select id="op" onchange="getProbabilityOf()">
<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>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
Before declaring the second function, nOC was declared local to function rollDice. But after I declared the next function, I needed to access it to complete step 4 (as mentioned in the code snippet). So I removed the variable nOC from the function and declared it globally(as shown in the code snippet).
The problem is that after declaring the variable as a global variable, none of the function was able to access it.
To resolve this problem, I rechecked the syntax many times but found no problems with it (as per my knowledge). I tried changing the type of the variable from let to var and const but still, the problem was not solved.
What could be the problem? As a new newbie in the field of coding, I know that small mistakes are made by me, but it is very important for me to know my mistakes and fix them.
It's generally not a good idea to use inline event handlers.
The error stems from the inline handlers. onchange="getProbabilityOf()" executes when the document renders. So after the page is loaded the onchange attribute will have the value of whatever result getProbabilityOf() returned. That won't be a javascript function I suspect.
Here are a few modifications to your code, making it work (technically). I have not checked if it's the right output, it's just some technical adjustments. Now you can use that as a base to continue your efforts.
About event delegation...
Not related to the code, but to 'number of cases' and for fun: What's a sample of size one worth?
// store a reference to #noc
const nOC = document.querySelector("#noc");
// add event handlers (event delegation)
document.addEventListener("click", rollDice)
document.addEventListener("change",
evt => {
if (evt.target.id === "op") {
return getProbabilityOf();
}
});
function rollDice(evt) {
if (evt.target.tagName !== "BUTTON") { return; }
//Number of trials
const nOT = +document.querySelector("#not").value;
const nocValue = +nOC.value;
// ^ retrieve #nOC value here
//Empty Array to be filled
let array = [];
//Loop which pushes random numbers in the empty array
for (let i = 1; i <= nOT; i += 1) {
array.push( Math.ceil(Math.random() * nocValue));
}
//Display results in a paragraph
document.querySelector("#para").innerHTML = `Your random numbers are ${array}`;
}
/*********************Get Probability**************************/
function getProbabilityOf() {
//Probability of...
const oP = +document.querySelector("#op").value;
//Check if the number is out of range. If no, then find the probability of given number
if (oP >= +nOC.value) {
// ^ determine #nOC value here
alert("This number is out of the range of possible outcomes that you have selected in step 1");
} else {
//Some code here
}
}
<!---------------------------Intro------------------------------>
<h1>Probability Finder</h1>
<hr/>
<p>With our probability finder, you can easily choose the number of possible cases and select the number of times you want to select a random case each time from the total cases and finally find the empirical probability of and case you want from the selected
total number of cases.</p>
<!---------------------------Step 1------------------------------>
<h3><span class="bold">Step 1 :</span>Select total number of cases:</h3>
<select id="noc">
<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>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<!---------------------------Step 2---------------------------->
<h3><span class="bold">Step 2 :</span>Select total number of trials</h3>
<select id="not">
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="50">50</option>
<option value="60">60</option>
<option value="70">70</option>
<option value="80">80</option>
<option value="90">90</option>
<option value="100">100</option>
</select>
<!----------------------------Step 3----------------------------->
<h3><span class="bold">Step 3 :</span>Get random numbers by experiment</h3>
<button>Get random numbers</button>
<p id="para"></p>
<!----------------------------Step 4----------------------------->
<h3><span class="bold">Step 4 :</span>Get probability of a particular number</h3>
<select id="op">
<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>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
Actually your script uses a DOM element and therefore must run after the DOM is loaded. You can do just use script just before closing body tag:
<!DOCTYPE html>
<html>
<head>
<title>Probability Finder</title>
</head>
<body>
<!---------------------------Intro------------------------------>
<h1>Probability Finder</h1>
<hr />
<p>
With our probability finder, you can easily choose the number of possible
cases and select the number of times you want to select a random case each
time from the total cases and finally find the empirical probability of
and case you want from the selected total number of cases.
</p>
<!---------------------------Step 1------------------------------>
<h3><span class="bold">Step 1 :</span>Select total number of cases:</h3>
<select id="noc">
<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>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<!---------------------------Step 2---------------------------->
<h3><span class="bold">Step 2 :</span>Select total number of trials</h3>
<select id="not">
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="50">50</option>
<option value="60">60</option>
<option value="70">70</option>
<option value="80">80</option>
<option value="90">90</option>
<option value="100">100</option>
</select>
<!----------------------------Step 3----------------------------->
<h3><span class="bold">Step 3 :</span>Get random numbers by experiment</h3>
<button onclick="rollDice()">Get random numbers</button>
<p id="para"></p>
<!----------------------------Step 4----------------------------->
<h3>
<span class="bold">Step 4 :</span>Get probability of a particular number
</h3>
<select id="op" onchange="getProbabilityOf()">
<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>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<script>
/*********************Select Random Number**********************/
//Number of cases
var nOC = document.getElementById('noc')
function rollDice () {
//Number of trials
let nOT = document.getElementById('not').value
//Empty Array to be filled
let array = []
//Loop which pushes random numbers in the empty array
for (let i = 1; i <= nOT; i++) {
array.push(Math.ceil(Math.random() * parseInt(nOC.value, 10)))
}
//Display results in a paragraph
document.getElementById('para').innerHTML =
'Your random numbers are ' + array
}
/*********************Get Probability**************************/
function getProbabilityOf () {
//Probability of...
let oP = document.getElementById('op').value
//Check if the number is out of range. If no, then find the probability of given number
if (oP >= parseInt(nOC.value, 10)) {
alert(
'This number is out of the range of possible outcomes that you have selected in step 1'
)
} else {
//Some code here
}
}
</script>
</body>
</html>

How to manipulate loops with input?

i got a for loop and i would like to manipulate the counter i with a input on screen. Below i can select from 1 to 10 and i want this selection to get replaced by the counter in the loop. That means when i choose 2, then i should be 2. I started with the code below, but document.getElementById('options').innerHTML = "i"; seems to be the wrong code to manipulate. Thanks so much for your help!
<select id="options" size="1">
<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>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
for (i=0, i<someArray; i++){
do somethingWith[i];}
document.getElementById('options').innerHTML = "i";
You need to get the value of the select element and assign that to i.
var i = document.querySelector('#options').value;
for(i < someArray; i++){
//code
}
Add this to HTML
<select onChange="doWork(this)">
In Js
function doWork(obj){
obj.innerHTML = obj.value
}
If want to do some thing on selection, use onchange method with select to trigger a function every time you are selecting an option.
<select id="options" size="1" onchange="myFunction()">
<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>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<p id="demo"></p>
<script>
function myFunction() {
var selectedValue = document.getElementById("options").value;
var somethingWith = [];
for (i=0; i < selectedValue; i++){
somethingWith.push(i);
}
document.getElementById('demo').innerHTML = somethingWith;
}
</script>
But if you only want to dynamically select an option in select tag, this might help
Select your favorite fruit:
<select id="mySelect">
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="pineapple">Pineapple</option>
<option value="banana">Banana</option>
</select>
<button type="button" onclick="myFunction()">banana</button>
<script>
function myFunction() {
document.getElementById("mySelect").value = "banana";
}
</script>

rael time counter for many selects

I have a dynamic list of products, and I need to know the total amount products selected by the users, for example 4 of product1, 5 of product5 and 6 of product9, so the value of the counter must be 15 (the adition of each product selected)
<select name="product1" id="product1" class="list-of-products">
<option value="0">0</option>
<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>
...
x products generated dynamically by php call
...
<select name="productx" id="productx" class="list-of-products">
<option value="0">0</option>
<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>
so my counter is like
<div id="counter">
<span id="counter-value">counter</span>
</div>
I've been thinking to do it using jquery,something like
$(document).ready(
function() {
var total = 0;
$('.list-of-products :selected').each(function(i, selected){
total= total+ parseInt($(selected).text());
});
$('#counter-value').text(total);
}
);
You're near the solution. Just check my fiddle:
$(document).ready(function () {
$('.list-of-products').change(function () {
var products = $('.list-of-products :selected');
var tot = calculateTotal(products);
$('#counter-value').text(tot);
});
});
// Function
function calculateTotal(product_list) {
var total = 0;
product_list.each(function (i, selected) {
total = total + parseFloat($(selected).text());
});
return total;
}
http://jsfiddle.net/hoja/3pznw838/

Adding several input boxes based by a select box value

I have a select box:
<select id="steps_number">
<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>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
Now, if the user selects "4", then 4 input boxes needed to be added to the page, if he changes his selection to 8, 8 input boxes need to be there, an so on...
And also, the input boxes names are important, I'm gonna send the form values to another page for processing and inserting the data into db, how I could know/get the newly made input boxes names?
Very simple example (also demonstrated here):
// bind to when the drop-down list changes
$('#steps_number').change(function(){
// find out the number to display
var count = $(this).val();
// Try to keep the fields already on the page. Remove anything
// that exceeds the count
$('#steps input:gt('+(count-1)+')').remove();
// But if it doesn't have enough, add more
for (var i = $('#steps input').length; i < count; i++){
$('<input>',{type:'text',id:'step'+(i+1),name='step'+(i+1)}).appendTo('#steps');
}
});
This assumes you want the following structure for your inputs:
<div id="steps">
<input type="text" id="step1" name="step1" />
<input type="text" id="step2" name="step2" />
<input type="text" id="step3" name="step3" />
<!-- .... -->
</div>
And with regards to server-side, you'll now see the inputs using $_REQUEST['step1'], $_REQUEST['step2'], etc. Or, depending on your form method, they'll show up in $_POST or $_GET as well.
I wrote for you some basic functionality. But you need to extend it for your needs:
$('#steps_number')​.change(function(){
for(var i=0; i < parseInt($(this).val()); i++) {
$('body').append('<input type="text" name="someinput' + i + '">');
}
});​
See on jsFiddle
You could do something like this:
<html>
<head>
<title>Test</title>
<script language="javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script language="javascript">
$(document).ready(function(){
alert("ok");
$("#steps_number").change(function() {
var inputNum = $("#steps_number").val();
var inputCode = "";
for(i=0; i<inputNum; i++) {
inputCode += "<p class=\"inputBox\"><input id=\"inputBox_" + i + "\" size=\"20\" type=\"text\"></p>"
}
$("#inputBoxes").html(inputCode);
});
});
</script>
</head>
<body>
<form id="testform">
<select id="steps_number">
<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>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<div id="inputBoxes">
</div>
</form>
</body>
</html>
Here is my solution:
<select id="steps_number">
<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>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<div id="container"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$("#steps_number").on("change", function() {
var count = $(this).val()
$("#container").html("")
for (i=0;i<count;i++) {
$("<input>").appendTo("#container");
$("<br>").appendTo("#container")
}
})
</script>

javascript out update onchange

I'm trying to get the javascript below to automatically update the input field (centimeters) below when a user select there height and inches. It should auto calculate the centimeters, and its not working.
<script type=​"text/​javascript">​
updateHeights:function(type){
if(type=='english'){
var feet=parseInt($F('feet'));
var inches=parseInt($F('inches'));
var cm=((feet*12+inches)*2.54).round();
$('centimeters').value=(feet?cm:'');
}
else
{
var cm=parseInt($F('centimeters'))||183;
if(cm>241||cm<91)cm=183;
var inches_total=(cm*0.3937).round();
var feet=(inches_total/12).floor();
var inches=inches_total%12;
$('feet').value=feet;
$('inches').value=inches;
$('centimeters').value=cm;
}
}
</script>
<label>Height:</label>
<select id="feet" name="add[feet]" onchange="Profile.updateHeights('english')">
<option value="">—</option>
<option value="7">7</option>
<option value="6">6</option>
<option value="5">5</option>
<option value="4">4</option>
<option value="3">3</option>
</select>ft.
<select id="inches" name="add[inch]" onchange="Profile.updateHeights('english')">
<option value="0">0</option>
<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>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
</select>in. or
<input id="centimeters" type="text" name="centimeters" maxlength="3" value="178" onchange="Profile.updateHeights('metric')" style="width: 30px;" />
centimeters
Assuming that this is just an excerpt from your entire code, Profile is a legitimate class name, and $F is defined somewhere, you're missing a few things.
First off, you're selecting by ID, so you need to include the # sign in your selectors.
Second, you're trying to parse an object as an integer. You need to use parseInt($("#feet").val()) to select the value contained in the input. Likewise, to set a value, you're going to want to use $("#centimeters").val(cm);

Categories

Resources