Count how many options a user chooses from multple selects - javascript

Let's say i've got 5 selects in an html form but you can only choose options from 3 of them. I need to accomplish the following: 1. calculate a total price, 2. dynamically pass set variables (that will eventually get passed to json for PHP) equal to the name attr of the selected options.
The problem i'm having is that i'm using value ="1" on every option. Then defining the price which is updated each time they select another option by statically assigning the variable with an if else. In what i'm doing each select has many options to choose from.
Where i'm stuck:
Either i'm going to use the name attribute and pass over 5 variables (using option:selected) or there is a way to accomplish this so my database only needs 3 columns to store to the database instead of 5.
I was hoping to accomplish this in the script on the page, rather than in the PHP. Can you do this dynamically and only send over 3 variables for JSON to pass off to the php or is this just going to be easier and faster to send over 5? Yes i'm very new to javascript and jquery :)
<form id = "testform" name = "testform" method="POST" action="test.php">
<select class = "choose" id="choice1">
<option value="0" selected=""></option>
<option value="1"> Choice 1.a</option>
</select>
<select class = "choose" id="choice2">
<option value="0" selected=""></option>
<option value="1"> Choice 1.b</option>
</select>
<select class = "choose" id="choice3">
<option value="0" selected=""></option>
<option value="1"> Choice 1.c</option>
</select>
<select class = "choose" id="choice4">
<option value="0" selected=""></option>
<option value="1"> Choice 1.d</option>
</select>
<select class = "choose" id="choice5">
<option value="0" selected=""></option>
<option value="1"> Choice 1.b</option>
</select>
<label><h4>Total:$</h4> <input style="" type="number" class="num" name="amount" value="0.00" readonly="readonly" /></label>
<script type="text/javascript">
$('select').change(function(){
var form = this.form;
var sum = 0;
var price;
$('select :selected').each(function() {
sum += Number($(this).val());
});
if (sum > 3) {
alert("You can only choose 3 classes");
$('select.choose').each(function() {
$('.choose').val(0);
});
}
if (sum == 1){
price = 80;
}
else if (sum == 2) {
price = 130;
}
else if (sum == 3) {
price = 180;
}
$(".num").val(price);
form.elements['total'] = price;
});

Check how many selects have a value of something other than 0, make sure it's not more than 3, then get the name of those selects
$('select').on('change', function(){
var selected = $('select').filter(function() {
return parseInt(this.value, 10) !== 0;
}),
sum = selected.length,
price = [80, 130, 180][sum - 1],
names = selected.map(function() {
return this.id; // selects don't seem to have names ?
}).get();
if (sum > 3) {
alert("You can only choose 3 classes");
} else {
$('.num').val(price);
}
console.log(names, sum)
});
FIDDLE

Related

How to count option values from different select options?

I have searched the web for answers and find none that I needed. So to the question. I am making a submit form (user selects fields and types an input number to determine the price of an order) which have 2 different select option fields and 1 input field.
<input type="text" id="number" placeholder="please enter a number">
(user entered 35 for example)</input>
<select id="firstpick">
<option value="50">Option 1</option>
<option value="150">Option 2</option>
<option value="100">Option 3</option>
</select>
<select id="secondpick">
<option value="10">Option 4</option>
<option value="15">Option 5</option>
<option value="20">Option 6</option>
</select>
<input disabled="disabled" type="text">(The total sum)</input>
I want to count sum of values for example: firstpick.option3 + (secondpick.option4 * number.35). In other meaning: 100 + (10 * 35) = 450. And I want to get that sum in a different disabled input field, so I can save it in database and show it to the user what is the total cost of an order by fields he selected and by number he typed in.
EDIT: The working code for you (the visitor)! http://jsfiddle.net/LoLd748n/4/
I am not entirely sure what you goal is, but this might be close. jQuery will be helpful.
function getSum() {
first = $("#firstpick").val();
second = $("#secondpick").val();
sum = first + second
return sum
}
It may be a good idea to add an event listener to your selects. This way your field will automatically update.
You do not have to have a disabled input, it could be type="hidden" instead. Then it will not show up on the page.
$("#firstpick").on("change", function() {
sum = getSum();
$("#my-hidden-input").val(sum);
});
$("#secondpick").on("change", function() {
sum = getSum();
$("#my-hidden-input").val(sum);
});

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" >

How to establish relationship between option tag of different select tags in html

I have three select tags in HTML with option tag.I want to establish relationship between option tags of different select tag.
EDIT-1
When I choose Reference-1 from select name="reference" then 2014-10-10 07:17:00 and 2014-10-10 08:46:00 from select name="from" and select name="to" should only be present in the dropdown list.When I choose Reference-2 then 2014-09-01 10:00:00 and 2014-09-01 11:00:00 should only be present in dropdown list of from and to select tag. My html code for is-
<form method="post">
Select Reference:
<select name="reference">
<option value="Select">Select</option>
<option value="Reference-1">Reference-1;</option>
<option value="Reference-2">Reference-2</option>
<option value="Reference-3">Reference-3</option>
<option value="Reference-4">Reference-4</option>
</select>
From Date:
<select name="from">
<option value="Select">Select</option>
<option value="2014-10-10 07:17:00">2014-10-10 07:17:00</option>
<option value="2014-09-01 10:00:00">2014-09-01 10:00:00</option>
<option value="2014-09-08 10:00:00">2014-09-08 10:00:00</option>
</select>
To Date:
<select name="to">
<option value="Select">Select</option>
<option value="2014-10-10 08:46:00">2014-10-10 08:46:00</option>
<option value="2014-09-01 11:00:00">2014-09-01 11:00:00</option>
<option value="2014-09-08 10:00:00">2014-09-08 11:00:00</option>
</select><br>
<b>Select Date to be compared</b>
<p>Date: <input type="text" id="datepicker"></p>
<input type="submit" value="Submit"><br>
</form>
Get the index of the selected option from reference select element and then disable all the options of from and to select elements except the option with index of the previous index you got from reference select option.
javaScript Solution :
var reference = document.getElementsByName("reference")[0];
var fromSelect = document.getElementsByName("from")[0];
var toSelect = document.getElementsByName("to")[0];
reference.onchange = function(){
var selectedIndex = this.selectedIndex;
for(var i = 1; i <= fromSelect.length; i++){
if(i != selectedIndex){
fromSelect.getElementsByTagName("option")[i].disabled = true;
toSelect.getElementsByTagName("option")[i].disabled = true;
} else{
fromSelect.getElementsByTagName("option")[i].disabled = false;
toSelect.getElementsByTagName("option")[i].disabled = false;
}
}
};
jsFiddle
jQuery Solution :
$("select[name='reference']").on("change", function(){
var $fromSelect = $("select[name='from']");
var $toSelect = $("select[name='to']");
var selectedIndex = $(this).children("option:selected").index();
$fromSelect.children("option").removeAttr("disabled");
$toSelect.children("option").removeAttr("disabled");
$fromSelect.children("option").not(":eq(" + selectedIndex +")").prop("disabled", "disabled");
$toSelect.children("option").not(":eq(" + selectedIndex +")").prop("disabled", "disabled");
});
jsFiddle
If second selection values are dependent on the first selection option, then you should disable the whole second selection until the first one is selected.
When the first one is selected then disable all the unrelated options in second selection and make it enabled to the user. Let me know if it helped.
$("select[name='reference']").on('change', function() {
var value = $(this).val(); // first selection value
if ("Reference-1" == value ) {
var $selection2 = $("select[name='from']");
$selection2.find("option[value*='2014-09-01 10:00:00']").prop('disabled',true);
$selection2.find("option[value*='2014-09-08 10:00:00']").prop('disabled',true);
}
...
});
Here is DEMO

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

<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.

Categories