How to find the sum of multiple select's selected options? - javascript

<select multiple name="item" style="width: 225px;" action="post" id="mySelect" onChange="document.getElementById('selectedValue').innerHTML = this.value;">
<option value="10">One
<option value="20">Two
<option value="30">Three
<option value="40">Four
<option value="50">Five
<option value="60">Six
</select>
<p>Total: <b><span id="selectedValue"></span></b></p>
I'm trying to get the total price displayed if multiple items are selected but it doesn't seem to be working for me. It's probably something simple but I can't get it. Any help greatly appreciated.

value property stores the last selected option's value, since you have a multiple select element, you can iterate through the selectedOptions collection of the HTMLSelectElement object:
document.getElementById('mySelect').addEventListener('change', function() {
var total = 0,
selected = this.selectedOptions,
l = selected.length;
for (var i = 0; i < l; i++) {
total += parseInt(selected[i].value, 10);
}
// ...
});
http://jsfiddle.net/qoft7mre/

onChange="document.getElementById('selectedValue').innerHTML = parseInt(document.getElementById('selectedValue').innerHTML || 0) + parseInt(this.value);"
This is not what you really want but you can sum like this.

Related

Two dynamic select boxes with data attribute in both and dependant on them

How to get dynamic select boxes dependant on the value of data attributes in both?
Got this code
HTML
<select id="hours" onchange="giveSelection()">
<option value="somethingA" data-option="1">optionA</option>
<option value="somethingB" data-option="2">optionB</option>
</select>
<select id="paxno">
<option data-option="1">optionC</option>
<option data-option="1">optionD</option>
<option data-option="2">optionE</option>
<option data-option="1">optionF</option>
</select>
JS
var sel1 = document.querySelector('#hours');
var sel2 = document.querySelector('#paxno');
var options2 = sel2.querySelectorAll('option');
function giveSelection() {
sel2.innerHTML = '';
for(var i = 0; i < options2.length; i++) {
if(options2[i].dataset.option === $("#hours").find(":selected").data("option")) {
sel2.appendChild(options2[i]);
}
}
}
I have been trying to do this from the example given on this question on Stackoverflow, and it is working when data-attribute is non numeric but data stored in both will be numeric.
Any thoughts what I am doing wrong here? is this the best approach to 2 dynamic select boxes with both having data attributes?
Since you're using jQuery, you might as well use it all the way.
To make it consistent, always use the jQuery data() method. data() will always try to intelligently convert the value of the data field to another type if it can determine that it is a number, or an object, or an array, or etc. So your original was comparing a dataset.option to a data(), using === which removes type coersion. So nothing would ever be equal.
var sel1 = $('#hours');
var sel2 = $('#paxno');
var options2 = sel2.find('option');
function giveSelection() {
var target = sel1.find(':selected').data('option');
sel2.empty().append(
options2.filter(function(){
return $(this).data('option') === target;
})
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="hours" onchange="giveSelection()">
<option value="somethingA" data-option="1">optionA</option>
<option value="somethingB" data-option="2">optionB</option>
</select>
<select id="paxno">
<option data-option="1">optionC</option>
<option data-option="1">optionD</option>
<option data-option="2">optionE</option>
<option data-option="1">optionF</option>
</select>

Using jquery data attributes with each function

I'm building a quote generator, and there is a product field where a user can select a product, select the quantity, then add another if they wish.
I'm using an each function to loop through all the products they add to sum the price.
For regular values, my JS is running great, but I want to add a second price (minimum price) that the product can be sold for. I've added the data as an attribute and i'm trying to use the same method to pull the price from the attribute, but it just keeps returning 'undefined'!!!!
HTML
<select class="form-control onChangePrice system1" name="SystemModel">
<option value="">Select...</option>
<option value="3300" data-min-price="3000">System 1</option>
<option value="4500" data-min-price="4000">System 2</option>
<option value="6000" data-min-price="5500">System 3</option>
<option value="6000" data-min-price="5500">System 4</option>
</select>
<div class="col-lg-3 col-md-3 col-sm-3">
<input class="form-control onChangePrice systemNumber" type="number" name="SystemModelAmount" value="1">
</div>
JS
var systemTotal = 0;
var systemMin = 0;
var i = 0;
$('.system1').each(function(){
if (this.value != "") {
systemEachMin = $(this).data("minPrice");
console.log(systemEachMin);
systemEachTotal = this.value * parseInt($(".systemNumber").eq(i).val());
systemTotal += parseFloat(systemEachTotal);
systemMin += parseFloat(systemEachMin);
};
i++;
});
The code works flawlessly for the regular value of the option, i just cant get it to repeat for the data attribute!
Thanks
You're doing a couple of things slightly wrong here:
$('.system1').each(function(){
should be:
$('.system1 option').each(function(){
and
systemEachMin = $(this).data("minPrice");
should be:
systemEachMin = $(this).data("min-price");
So in full:
var systemTotal = 0;
var systemMin = 0;
var i = 0;
$('.system1 option').each(function(){
if (this.value != "") {
systemEachMin = $(this).data("min-price");
console.log(systemEachMin);
systemEachTotal = this.value * parseInt($(".systemNumber").eq(i).val());
systemTotal += parseFloat(systemEachTotal);
systemMin += parseFloat(systemEachMin);
};
i++;
});
$(this).data("minPrice"); refers to the select tag and not the options tag, there is no data-min-price on the select tag.
this.options will return all the options in an array
or you could use the following for the selected options data attribute
$(this).find('option:selected').data("minPrice")
or
$("option:selected", this).data("minPrice")

Capture all dropdown/select elements value with onclick and insert html total field

We are using a html quiz application that does not contain a total field for dropdowns/select elements. I would like to insert a html div total that captures ALL select elements with values while using click to capture changes. I've found pieces of my solution while searching but can't seem to put them all together. I don't have the ability to insert the eventlistener into the html directly.
What I have so far. Feel like im close but receiving x[i] not defined.
var x = document.getElementsByTagName("select");
var i = 1;
sum = 0;
for (i; i < x.length; i++) {
x[i].addEventListener("click", function(){
sum += Number(x[i].value);
});
}
All dropdowns are in the same repeated class:
<select class="qm_SELECT_sel"><option value=""></option>
you getting x[i] as undefined because click even is bind with all of the select element but while firing click event in i it always passes the last valid of i
for example : if you have 3 dropdowns then it will click event with 3 of them but while clicking any dropdown it always passes 3.
to ignore this u had to kept that event bind to saperate function and pass element as a parameter to that function in this way value of each i is maintained
var x = document.getElementsByTagName("select");
var i = 1;
sum = 0;
for (i; i < x.length; i++) {
bindSelectClick(x[i]);
}
function bindSelectClick(elem){
elem.addEventListener("click", function(){
sum += Number(elem.value);
});
}
As per Your comment the finale answer is
$('.qm_SELECT_sel').change(function(){
var sum=0;
$('.qm_SELECT_sel option:selected').each(function(){
sum =Number(sum)+Number($(this).val());
});
$('#total_filed').val(sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="1as" class="qm_SELECT_sel">
<option value="" >select 1 </option>
<option value="1" >1 </option>
<option value="2" >2</option>
</select>
<select name="2asa" class="qm_SELECT_sel" >
<option value="" >select 2 </option>
<option value="1" >1 </option>
<option value="2" >2</option>
</select>
<input name="input_field" id="total_filed" >

Chosen select box with multiple selected values on page load

I'm trying to select multiple values on page load, but it only selects the last value on the array. Take a look at the code
jQuery("#language").chosen();
var str = '12,24,36';
var languageArray = str.split(',');
for (var i = 0; i < languageArray.length; i++) {
jQuery("#language").val(languageArray[i]);
jQuery("#language").trigger("liszt:updated");
}
I get only 36 selected on page load, is there anything wrong with the js ?
Here is the HTML for the select
<select name="language[]" id="language" data-placeholder="Choose Language..." multiple="multiple">
I appreciate your help.
Thanks
You can select multiple options in a multi-value select box by passing an array to the val() method.
Example
Markup
<select name="language" id="language" data-placeholder="Choose Language..." multiple="multiple">
<option value="en">English</option>
<option value="fr">French</option>
<option value="de">German</option>
</select>
JavaScript
var str = 'en,de';
jQuery("#language").val(str.split(','));
And here's a jsFiddle for funsies.
you could set the selected property of matched option element. hope it would help.
var values = ['1', '2', '4'];
$('#languages').find('option').filter(function (idx, option) {
if($.inArray(option.value, values) !== -1) {
return option;
}
}).prop('selected', 'true');

JavaScript to select multiple select list values

I have the following select list from which the user can select multiple values.
<select name="valumethod1[]" id="valumethod1[]" onBlur="validatevalumethod()" size="6">
<option value ="t1">test1</option>
<option value ="t2">test2</option>
<option value ="t3">test3</option>
<option value ="t4">test4</option>
</select>
I want to fetch the selected values in JavaScript, but I don't know how to do this. Please help me.
Try something like this :
var ob = document.getElementById('valumethod1[]');
var selected = new Array();
for (var i = 0; i < ob.options.length; i++) {
if (ob.options[ i ].selected) {
selected.push(ob.options[ i ].value);
}
}
The array selected is then an array of selected options. Working example here
Note: you need to add multiple="multiple" to your select list as an attribute

Categories