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/
Related
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>
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>
HTML
<select id="my-select" multiple="multiple" size="8" style="width:200px">
<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>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
</select>
JQUERY
$('#my-select option').on('click',function(){
var count = $('#my-select').find('option:selected').length;
$('#dg').html(count);
if(count>10){
$(this).attr('selected',false);
alert('limit 10');
}
});
http://jsfiddle.net/LxNMm/
When you click on the options, calculate count of selected options and limit it to 10, but if you click on the options with pressing shift key and select a range, selection could be greater than 10. How can a detect count of selected options when select a range with pressing shift key
You can try updating the values this way:
$('#my-select').on('change', function () {
var count = $(this).find('option:selected').length;
$('#dg').html(count);
if (count > 10) {
$('option:gt(9)', this).attr('selected', false);
count = $(this).find('option:selected').length;
$('#dg').html(count);
alert('error');
}
});
Your updated demo fiddle
Don't use the click event of the <option />s but the change event of the <select />
$('#my-select').on('change', function () {
var count = $(this).find('option:selected').length;
$('#dg').html(count);
if (count > 10) {
$(this).find("option").prop('selected', false);
alert('error');
}
})
fiddle
This question is based on THIS QUESTION
When an option from one of the SELECT boxes were selected, I wanted the rest to be repopulated, without said option, but instead, is there an easy way to loop through all these select items, to ensure the same option hasn't been selected twice?
Thanks.
Person Number 1
<select name="person1">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
Person Number 2
<select name="person2">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
Person Number 3
<select name="person3">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
Basic Overview:
JavaScript loop to ensure none of the options have been selected twice?
<!DOCTYPE html>
<html>
<head>
<script>
function doAction(el) {
for (var i = 0; i < document.getElementById('person2').length; i++) {
var v = (i != el.selectedIndex ? '' : 'disabled');
document.getElementById('person2')[i].disabled = v;
if (document.getElementById('person2').selectedIndex == el.selectedIndex)
document.getElementById('person2').selectedIndex = 0;
document.getElementById('person3')[i].disabled = v;
if (document.getElementById('person3').selectedIndex == el.selectedIndex)
document.getElementById('person3').selectedIndex = 0;
}
}
</script>
</head>
<body>
Person Number 1
<select id="person1" onchange="doAction(this)" >
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br/>
Person Number 2
<select id="person2">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br/>
Person Number 3
<select id="person3">
<option value="null">Please Select an option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</body>
</html>
If you use
var x = document.getElementByName('person1').value;
var y = document.getElementByName('person2').value;
var z = document.getElementByName('person3').value;
you can get the values. Then, you have 3 items, to compare against all of them you just have to do 3 checks:
if(x == y || x == z || y == z){
...
}
Or you could throw all of the values into an array, and then splice out the first occurrence, and then check to see if it occurs again.
//get all selects
var selects = document.getElementsByTagName('select');
var setOfPeople = [];
for(i in selects){
setOfPeople[i] = selects[i].name;
}
var selections = [];
//put everything in an array
for(i in setOfPeople){
selections[i] = document.getElementByName(setOfPeople[i]).value;
}
for(i in setOfPeople){
var val = document.getElementByName(setOfPeople[i]).value;
//make sure the element is in the selection array
if(selections.indexOf(val) != -1){
//rip out first occurrence
selections.splice(selections.indexOf(val), 1);
}
//check for another occurrence
if(selections.indexOf(val) != -1){
...
}
}
Excually Im not a programmer, but Im trying to learn how to make a questionnaire with html and javascript:
I have four selection boxes in a form. Each one of the selection boxes has the values through 0 to 10. The main rule of this questionnaire is to change the value of all four selection boxes so that it adds up to 10.
I figured out the following solution:
instant updated text box where it calculates the total value selected (with onChange);
validate at submit button if a total value of 10 (and not more or less) is selected.
Alternatively I would even assign a (error) message instantly when the user selects a value that exceeds the total value of 10.
I have some half baked javascripts, but I don't have enough understanding of the subject to excually connect the dots. Hope you can help me.
Tim
My framework:
<html>
<head>
<script type="text/javascript">
function editTotalValue(){
}
function validateTotalValue(){
}
</script>
</head>
<body>
<form name="form1">
<select name="question1" onChange="editTotalValue();">
<option selected 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>
</select>
<select name="question2" onChange="editTotalValue();">
<option selected 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>
</select>
<select name="question3" onChange="editTotalValue();">
<option selected 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>
</select>
<select name="question4" onChange="editTotalValue();">
<option selected 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>
</select>
<!-- Show total value selected in text box -->
<input name="totalValue" type="text" maxlength="2" readonly="true">
<!-- Validate that totalValue(); is indeed 10 and not more or less and pass on the data -->
<input name="submit" type="button" onClick="validateTotalValue();">
</form>
</body>
</html>
Here's something more in-depth that you can play with:
document.getElementById("form1").onsubmit = checkTarget;
function checkTarget(evt)
{
var el;
if(window.event)
{
//checking for IE equivalent
el = window.event.srcElement;
}else if(evt.target)
{
el = evt.target;
}
if(window.event)
{
//checking for IE equivalent
window.event.returnValue = false;
}else if(evt.preventDefault)
{
evt.preventDefault();
}
calculateValues(el);
}
function calculateValues(form)
{
var values = [];
var value = 0;
for(var i=0;i<form.elements.length;i++)
{
var el = form.elements[i];
if(el.tagName === "SELECT")
{
values.push(el.value);
}
}
for(var j=0;j<values.length;j++)
{
value = value + parseInt(values[j], 10);
}
updateValue(value);
checkValue(values, value);
}
function updateValue(value)
{
document.getElementById("result_box").value = value;
}
function checkValue(values, value)
{
var temp = [];
for(var i=0;i<values.length;i++)
{
if(values[i] > 0 && values[i] < 10)
{
temp.push(values[i]);
}
}
if(value === 10 && temp.length === 4)
{
document.getElementById("message_box").value = "You win!";
}else if(value > 10 && temp.length === 4)
{
document.getElementById("message_box").value = "Value is more than 10";
}
}
http://jsfiddle.net/YS6mm/9/
Tested as working in: Firefox 4, IE8, IE8 Compatibility View (Quirks), IE7 Quirks Mode, Chrome 4, Safari 4, and Opera 11.
function editTotalValue() {
var val = 0;
for (var i = 1; i < 5; i++) {
val = val + document.getElementById("question" + i).value;
}
var display = document.getElementbyId("totalValue");
if (val > 10) {
alert("error");
} else {
display.value = val;
}
}