I have 3 dropdown with values N/A, 3, 5, 6. On change event if I change value of first drop down the count should be 1 always but whenever I change again value is keep increasing. I know my counter is wrong but not getting idea to fix it.
$count = 0;
$maxcount = 3;
$arrOfLevel2ElementId.each(function () {
arrOfLevel2ElementId = $(this).attr('id');
$("#" + arrOfLevel2ElementId).on('change', function () {
level2ElementVal = $(this).val();
if (level2ElementVal == "N/A") {
if ($count > 0) {
$count--;
} else {
$count;
}
showOutput($sum);
return false;
} else {
if ($count <= $maxcount) {
$count++;
} else {
$count;
}
alert($count);
$sum = parseInt(level2ElementVal);
showOutput($sum);
}
This is the case because as soon as you change the dropdown, you call the function.
Here you state that if(level2ElementVal == "N/A") you decrease the count.
But in the else statement, meaning you select either 3, 5 or 6, you check if the count isn't at the maxcount. Which is not the case if $count = 1. Then you increase it. Which explains that it increases when you change the value.
I'm not sure why you have a $maxcount, but if you were to change it to 1, my assumption is that your count should not exceed 1.
EDIT:
If what I've understand correctly from your comments you want to device the three numbers, unless its on N/A.
Try this fiddle:
https://jsfiddle.net/7b21b699/1/
It sets the value field when the last field is changed and checks the values at that point. Then sums them up when needed and divides them correctly.
$("#box3").on('change', function(){
var val1 = $("#box1").val();
var val2 = $("#box2").val();
var val3 = $("#box3").val();
var sum = 0;
var count = 0;
if(val1 != "N/A"){
sum += parseInt(val1);
count++;
}
if(val2 != "N/A"){
sum += parseInt(val2);
count++;
}
if(val3 != "N/A"){
sum += parseInt(val3);
count++;
}
var result = sum / count;
$("#value").text(result);
});
<select class="form-control" id="box1" name="a">
<option value="" selected="selected">Select a value</option>
<option value="N/A">N/A</option>
<option value="3">3</option>
<option value="5">5</option>
<option value="7">7</option>
<option value="10">10</option>
</select>
<select class="form-control" id="box2" name="a">
<option value="" selected="selected">Select a value</option>
<option value="N/A">N/A</option>
<option value="3">3</option>
<option value="5">5</option>
<option value="7">7</option>
<option value="10">10</option>
</select>
<select class="form-control" id="box3" name="a">
<option value="" selected="selected">Select a value</option>
<option value="N/A">N/A</option>
<option value="3">3</option>
<option value="5">5</option>
<option value="7">7</option>
<option value="10">10</option>
</select>
<div id ="value">value comes here</div>
Related
I have some problems about option select.
I want the select option auto disable if user didn't pick size t-shirt. And in total order the option select max order same with stock size t-shirt.
Exam :
Size S have a 15 stock
Size M have a 20 stock
And in the option select max order corresponding with stock of size t-shirt.
If user pick size s the option select order auto max number to 15, and user pick size m the option select order auto max number to 20.
And about the number stock get from database
I'm use codeigniter with bootstrap
This my code :
Select Option Size T-Shirt
<?php
$sprod = $stok['stok_s'];
$mprod = $stok['stok_m'];
$lprod = $stok['stok_l'];
if ($sprod == 0 && $mprod != 0 && $lprod != 0) {
echo '<select name=produk_size id=produk_size class=form-control onchange=proses_stok() style=width:95%>
<option value=0>Select Size:</option>
<option value=stok_s disabled>s</option>
<option value=stok_m>m</option>
<option value=stok_l>L</option>
</select>';
?>
Option Select Order Number
<select name="produk_stok" id="produk_stok" class="form-control" style="width:95%">
<?php
$stok_prod = $stok['stok_s'] + $stok['stok_m'] + $stok['stok_l'];
if ($stok_prod == 0 )
{
echo "<option value=0> 0 </option>";
}
else{
for($a=$stok['min_buy'];
$a<=$stok['stok']; $a+=1)
{
echo "<option value=$a>$a</option>";
}
}
?>
</select>
Javascript
<script type="text/javascript">
function proses_stok(){
var produk_stock = document.getElementById("produk_size").value;
document.getElementById("produk_stock").value=produk_stock;
}
</script>
And when I change the size the option select number didn't change. And when i'm select "select size" the option select number order didn't disable/just 0 stock
You can use for-loop to make all options disabled from a particular values this value will get passed to a function where we will get the length of options in select-box and then use this under loop to disabled options from select-box .
Demo Code :
function proses_stok() {
var produk_stock = document.getElementById("produk_size").value;
document.getElementById("produk_stok").value = produk_stock;
//if value is small
if (produk_stock == "stok_s") {
disable_values(15); //disable from
} else if (produk_stock == "stok_m") {
disable_values(20); //disable from
} else {
//enable all options
$("#produk_stok option").prop('disabled', false);
}
}
function disable_values(start) {
var s = document.getElementById("produk_stok");
var end = s.options.length; //getting length of option
//first enabled all options
$("#produk_stok option").prop('disabled', false);
//loop through all options
for (var i = start; i < end; i++) {
s.options[i].disabled = true; //disabled
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name=produk_size id=produk_size class=form-control onchange=proses_stok() style=width:95%>
<option value=0>Select Size:</option>
<option value=stok_s>s</option>
<option value=stok_m>m</option>
<option value=stok_l>L</option>
</select>
<select name="produk_stok" id="produk_stok" class="form-control" style="width:95%">
<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>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
</select>
Update 1 :
To add options till specific values you can use for loop pass the end value to it and then append data to some variable and then append this data using innerHTML to show under select-box.
Demo Code :
function proses_stok() {
var produk_stock = document.getElementById("produk_size").value;
//if value is small
if (produk_stock == "stok_s") {
disable_values(15); //add till this option
} else if (produk_stock == "stok_m") {
disable_values(20); //add till this option
} else if(produk_stock == "0") {
document.getElementById("produk_stok").innerHTML = "<option value='0'>0</option>";
}else{
//if large size select
//do somthing ..
}
}
function disable_values(end) {
var s = document.getElementById("produk_stok");
var data="";
//loop through all options
for (var i = 1; i <= end; i++) {
//append options
data +="<option value="+i+">"+i+"</option>";
}
//add data to select box
s.innerHTML= data;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name=produk_size id=produk_size class=form-control onchange=proses_stok() style=width:95%>
<option value=0>Select Size:</option>
<option value=stok_s>s</option>
<option value=stok_m>m</option>
<option value=stok_l>L</option>
</select>
<select name="produk_stok" id="produk_stok" class="form-control" style="width:95%">
<option value="0">0</option>
</select>
I don't know how to go about calculating the price of 4 select options,
So as you can see in the HTML code, there's 5 divisions to a rank, and a total of 5 ranks.
A guide on the input of Bronze 5 to Bronze 1 would = ($0 + $2 + $4 + $4 + $8)
Bronze Division 5 = $0
Bronze Division 4 = $2
Bronze Division 3 = $4
Bronze Division 2 = $6
Bronze Division 1 = $8
Silver Would also be the same with different prices, and so on to diamond.
Another example is here: https://i.gyazo.com/177ce3443967600e12a4d42636a5db69.png
This shows an order of bronze division 5, to silver division 3. It runs through all the stored prices for each division on the selected rank and adds them until it reaches the last input.
I hope this is enough information to help you understand what I mean.
var current_division,
desired_division;
function current1() {
var Amt = document.priceCalc.CRANK1;
var Qty = document.priceCalc.CRANK2;
return parseInt(Qty.value) * parseFloat(Amt.value);
}
function desiredd() {
var Amt = document.priceCalc.DRANK1;
var Qty = document.priceCalc.DRANK2;
return price = parseInt(Qty.value) * parseFloat(Amt.value);
}
function total() {
if (isNaN(current1())) {
current_division = 0;
} else {
current_division = current1();
}
if (isNaN(desiredd())) {
desired_division = 0;
} else {
desired_division = desiredd();
}
var totalPrice = (current_division + desired_division);
document.getElementById('prices').value = totalPrice;
document.getElementById("prices").readOnly = true;
}
document.getElementById('divboost').addEventListener('change', function() {
total();
})
<form id="divboost" name="priceCalc" action="">
<br/>
<select id="CRANK1"> Current Rank
<option value="0">Bronze</option>
<option value="1">Silver</option>
<option value="2">Gold</option>
<option value="3">Platinum</option>
<option value="4">Diamond</option>
</select>
<br>
<br/>
<select id="CRANK2"> Current Divison
<option value="5">Division 5</option>
<option value="6">Division 4</option>
<option value="7">Division 3</option>
<option value="8">Division 2</option>
<option value="9">Division 1</option>
</select>
<br>
<br>
<br/>
<br/>
<select id="DRANK1"> Desired Rank
<option value="0">Bronze</option>
<option value="1">Silver</option>
<option value="2">Gold</option>
<option value="3">Platinum</option>
<option value="4">Ddiamond</option>
</select>
<br>
<br/>
<select id="DRANK2"> Desired Divison
<option value="5">Division 5</option>
<option value="6">Division 4</option>
<option value="7">Division 3</option>
<option value="8">Division 2</option>
<option value="9">Division 1</option>
</select>
<br>
<br>
<input type="text" id="prices">
<br/>
<br>
</form>
I understand that you need to follow fixed prices (it would not be a simple math equation).
For that reason I recommend you use an array on your code to hold the values for all prices. You would need to update the javascript array to represent the correct values.
Dividing prices on ranks/divisions is pointless. Instead of having two separate lists, you can merge two in one: B5, B4, B3, B2, B1, S5, S4, ... (where B=Bronze and S=Silver).
So you have one single list of prices. What you need to do is get what index at the array is the current rank + division, and what index at the array is the desired rank + division.
When you have those two values, you just need to sum all values from the current index to the desired index, thus getting the accumulated values.
Also I recommend warning the user if they select a less rank/division than they currently are, or otherwise the price would be negative (having a surprising economic impact).
I added the first 3 ranks, you can do the remaining 2. From an UX point of view, I honestly recommend using a single select, since there are not too many values, and it would mean less clicks for the user. If you want to go that route, let me know and I will update the script.
Show warning if user selected invalid rank/division (simpler)
var current_division,
desired_division;
// These are the flattened prices for all divisions.
// First is bronze div5, second is bronze div4, bronze div3,
// bronze div2, bronze div1, silver div 5, etc.
// You would need to add the remaining ranks and update the prices.
var prices = [
00,02,04,06,08,
10,12,14,16,18,
20,22,24,26,28
];
function getCurrentIndex() {
return (+document.getElementById("CRANK1").value +
+document.getElementById("CRANK2").value);
}
function getDesiredIndex() {
return (+document.getElementById("DRANK1").value +
+document.getElementById("DRANK2").value);
}
function total() {
var currentIndex = getCurrentIndex();
var desiredIndex = getDesiredIndex();
// If desiredIndex is greater than currentIndex, warn the user
// that they can't go from high to low!
if (desiredIndex < currentIndex) {
document.getElementById('prices').value = "You can't rank backwards";
return;
}
// Now you need to start summing the prices from currentIndex
// to desiredIndex.
var accumulatedPrice = 0;
for(var i = currentIndex; i <= desiredIndex; i++) {
accumulatedPrice += prices[i];
}
document.getElementById('prices').value = accumulatedPrice;
document.getElementById("prices").readOnly = true;
}
document.getElementById('divboost').addEventListener('change', function() {
total();
})
<form id="divboost" name="priceCalc" action="">
<br/>
<select id="CRANK1"> Current Rank
<option value="0">Bronze</option>
<option value="5">Silver</option>
<option value="10">Gold</option>
</select>
<br>
<br/>
<select id="CRANK2"> Current Divison
<option value="0">Division 5</option>
<option value="1">Division 4</option>
<option value="2">Division 3</option>
<option value="3">Division 2</option>
<option value="4">Division 1</option>
</select>
<br>
<br>
<br/>
<br/>
<select id="DRANK1"> Desired Rank
<option value="0">Bronze</option>
<option value="5">Silver</option>
<option value="10">Gold</option>
</select>
<br>
<br/>
<select id="DRANK2"> Desired Divison
<option value="0">Division 5</option>
<option value="1">Division 4</option>
<option value="2">Division 3</option>
<option value="3">Division 2</option>
<option value="4">Division 1</option>
</select>
<br>
<br>
<input type="text" id="prices">
<br/>
<br>
</form>
Hide invalid options (more complex)
var current_division,
desired_division;
// These are the flattened prices for all divisions.
// First is bronze div5, second is bronze div4, bronze div3,
// bronze div2, bronze div1, silver div 5, etc.
// You would need to add the remaining ranks and update the prices.
var prices = [
00,02,04,06,08,
10,12,14,16,18,
20,22,24,26,28
];
function getIndex(rankNode, divisionNode) {
return +rankNode.value + +divisionNode.value;
}
// show: can be a boolean or a function filter
function showHTMLCollection(htmlCollection, show) {
if (!htmlCollection || htmlCollection.length === 0) return;
show = typeof show === "undefined" ? true : show;
for (var i = 0; i < htmlCollection.length; i++) {
var computedShow = typeof show === "function" ? show(htmlCollection[i]) : show;
htmlCollection[i].disabled = !computedShow;
htmlCollection[i].style.display = computedShow ? "" : "none";
}
}
function validateSelectValue(selectNode) {
// If <select> has selected a disabled <option>, set to first valid value
var selectedOptionNode = selectNode.querySelector("option[value='" + selectNode.value + "']");
if (selectNode.value == "" || selectedOptionNode.disabled) {
for (var i = 0; i < selectNode.children.length; i++) {
if (!selectNode.children[i].disabled) {
selectNode.value = selectNode.children[i].value;
return;
}
}
// There's no more valid values on the list, set to empty
selectNode.value = "";
}
}
function total() {
var currentRankNode = document.getElementById("CRANK1");
var currentDivisionNode = document.getElementById("CRANK2");
var currentIndex = getIndex(currentRankNode, currentDivisionNode);
var desiredRankNode = document.getElementById("DRANK1");
var desiredDivisionNode = document.getElementById("DRANK2");
var desiredIndex = getIndex(desiredRankNode, desiredDivisionNode);
var desiredRankChildren = desiredRankNode.children;
// Hide ranks based on filter
showHTMLCollection(desiredRankChildren, function(option) {
// Show only desired ranks greater than the current rank,
// or if same rank, we are not on the last division
// otherwise we can't keep ranking
return (option.value > +currentRankNode.value ||
(option.value == +currentRankNode.value && +currentDivisionNode.value < 4));
});
// Make sure that the desired ranks select contains valid value
validateSelectValue(desiredRankNode);
var desiredDivisionChildren = desiredDivisionNode.children;
// Hide divisions based on filter
showHTMLCollection(desiredDivisionChildren, function(option) {
// If greater rank, show all divisions. If same rank,
// show only desired divisions greater than the current divisions
return (+desiredRankNode.value > +currentRankNode.value ||
(+desiredRankNode.value == +currentRankNode.value && option.value > +currentDivisionNode.value));
});
// Make sure that the desired ranks select contains valid value
validateSelectValue(desiredDivisionNode);
// Now you need to start summing the prices from currentIndex
// to desiredIndex.
var accumulatedPrice = 0;
for(var i = currentIndex; i <= desiredIndex; i++) {
accumulatedPrice += prices[i];
}
document.getElementById('prices').value = accumulatedPrice;
document.getElementById("prices").readOnly = true;
}
document.getElementById('divboost').addEventListener('change', function() {
total();
})
<form id="divboost" name="priceCalc" action="">
<br/>
<select id="CRANK1"> Current Rank
<option value="0">Bronze</option>
<option value="5">Silver</option>
<option value="10">Gold</option>
</select>
<br>
<br/>
<select id="CRANK2"> Current Divison
<option value="0">Division 5</option>
<option value="1">Division 4</option>
<option value="2">Division 3</option>
<option value="3">Division 2</option>
<option value="4">Division 1</option>
</select>
<br>
<br>
<br/>
<br/>
<select id="DRANK1"> Desired Rank
<option value="0">Bronze</option>
<option value="5">Silver</option>
<option value="10">Gold</option>
</select>
<br>
<br/>
<select id="DRANK2"> Desired Divison
<option value="0" disabled style="display: none">Division 5</option>
<option value="1" selected>Division 4</option>
<option value="2">Division 3</option>
<option value="3">Division 2</option>
<option value="4">Division 1</option>
</select>
<br>
<br>
<input type="text" id="prices">
<br/>
<br>
</form>
As you can see here: Entire form onChange , with pure JS you can't add a change listener to an entire form at once. You need to add a listener to each element inside it that you want to change. The code below shows how.
Also, I don't know the values for each "Color" (bronze, silver, etc...), so I invented the values, increasing each one by 2... The math used is:
The "Color" value is the multiplier, and the "Division" value is the real value. So,
Bronze (multiplier 2) * Division 4 (value 2) equals = $ 6
The values and numbers you should adjust accordling to your needs, but I think the logic here will help you. Probably you will need more than just set value to the options, it woulb be better to store the values in an object or array and then get the values from there, it would help in more complex math needs.
See the code below, clicking to show Snippet, and tell me if this helps you.
var current_division,
desired_division;
function current1() {
var Amt = document.priceCalc.CRANK1;
var Qty = document.priceCalc.CRANK2;
return parseInt(Qty.value) * parseFloat(Amt.value);
}
function desiredd() {
var Amt = document.priceCalc.DRANK1;
var Qty = document.priceCalc.DRANK2;
return price = parseInt(Qty.value) * parseFloat(Amt.value);
}
function total() {
if (isNaN(current1())) {
current_division = 0;
} else {
current_division = current1();
}
if (isNaN(desiredd())) {
desired_division = 0;
} else {
desired_division = desiredd();
}
var totalPrice = (current_division + desired_division);
document.getElementById('prices').value = totalPrice;
document.getElementById("prices").readOnly = true;
}
var changers = document.getElementsByClassName('changer');
for (var i =0; i < changers.length; i++){
var changer = changers[i];
changer.addEventListener('change', function() {
total();
})
}
<form id="divboost" name="priceCalc" action="">
<br/>
<select id="CRANK1" class='changer'> Current Rank
<option value="2">Bronze</option>
<option value="4">Silver</option>
<option value="6">Gold</option>
<option value="8">Platinum</option>
<option value="10">Diamond</option>
</select>
<br>
<br/>
<select id="CRANK2" class='changer'> Current Divison
<option value="0">Division 5</option>
<option value="1">Division 4</option>
<option value="2">Division 3</option>
<option value="3">Division 2</option>
<option value="4">Division 1</option>
</select>
<br>
<br>
<br/>
<br/>
<select id="DRANK1" class='changer'> Desired Rank
<option value="2">Bronze</option>
<option value="4">Silver</option>
<option value="6">Gold</option>
<option value="8">Platinum</option>
<option value="10">Diamond</option>
</select>
<br>
<br/>
<select id="DRANK2" class='changer'> Desired Divison
<option value="0">Division 5</option>
<option value="1">Division 4</option>
<option value="2">Division 3</option>
<option value="3">Division 2</option>
<option value="4">Division 1</option>
</select>
<br>
<br>
$ <input type="text" id="prices">
<br/>
<br>
</form>
I have select boxes, and they have data attribute (data-price). I want to sum selected option "data-price" as "total" . but I have one problem. If I select only value="bmw" or I have not selected anything it gives me NaN$.
$('#mark, #series').on('change', function() {
var $selected = $('#mark, #series').children(":selected");
var sum = 0;
$selected.each(function() {
sum += $(this).data('price');
});
$('#total').html(sum + '$');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="mark" name="mark">
<option value="">--</option>
<option value="bmw" data-price="200">bmw</option>
<option value="audi" data-price="400">audi</option>
</select>
<select id="series" name="series">
<option value="">--</option>
<option value="series-1" data-price="2000" >3 series</option>
<option value="series-1" data-price="3000" >5 series</option>
</select>
<div id="total"> </div>
This code will fix your problem:
$('#mark, #series').on('change', function() {
var $selected = $('#mark, #series').children(":selected");
var sum = 0;
$selected.each(function() {
var price = $(this).data('price');
if(price){
sum += $(this).data('price');
}
});
$('#total').html(sum + '$');
});
If you log the pricevariable into the forEach loop, you can see that it returns an integer and then an undefined. That should be fixed! :)
When you select only one option the selected option of the other does not have a 'data-price' attribute:
<option value="">--</option> <!-- data-price === "undefined" -->
You could set a default of "0" to the initially selected option:
<option value="" data-price="0">--</option>
Example:
$('#mark, #series').on('change', function() {
var $selected = $('#mark, #series').children(":selected");
var sum = 0;
$selected.each(function() {
sum += $(this).data('price');
});
$('#total').html(sum + '$');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="mark" name="mark">
<option value="" data-price="0">--</option>
<option value="bmw" data-price="200">bmw</option>
<option value="audi" data-price="400">audi</option>
</select>
<select id="series" name="series">
<option value="" data-price="0">--</option>
<option value="series-1" data-price="2000">3 series</option>
<option value="series-1" data-price="3000">5 series</option>
</select>
<div id="total"> </div>
When you change one dropdown, let's say Make, $selected will include two elements:
<option value="bmw" data-price="200">bmw</option> and <option value="">--</option>
When you are now calculating the sum, you are adding two values 200 and and empty string as strings. You should try to parse all values to integers with parseInt("string", 10) (Note the 10 parameter which specifies the base to be used, it's good practice to be explicit, see parseInt documentation here).
Also, as other answers here state, you should always try to default to an integer value (in the case of the empty string). So your code could now be like this:
$('#mark, #series').on('change', function() {
var $selected = $('#mark, #series').children(":selected");
var sum = 0;
$selected.each(function() {
var optionPrice = parseInt($(this).data('price'), 10) || 0;
sum += optionPrice;
});
$('#total').html((sum) ? (sum + '$') : '');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="mark" name="mark">
<option value="">--</option>
<option value="bmw" data-price="200">bmw</option>
<option value="audi" data-price="400">audi</option>
</select>
<select id="series" name="series">
<option value="">--</option>
<option value="series-1" data-price="2000" >3 series</option>
<option value="series-1" data-price="3000" >5 series</option>
</select>
<div id="total"> </div>
You must to parse your data which is seen as a string
$selected.each(function() {
var data = $(this).data('price');
if(data != undefined){
sum += parseFloat(data);
}
});
Please use a fallback value of 0 if the returned value is undefined.
using the line.
sum += $(this).data('price') || 0;
Note: You also need to run this validation function at the beginning to ensure, the result is calculated at the beginning before the change() event.
function validate(){
var $selected = $('#mark, #series').children(":selected");
var sum = 0;
$selected.each(function() {
sum += $(this).data('price') || 0;
});
$('#total').html(sum === 0 ? '' : sum + '$');
}
validate();
$('#mark, #series').on('change', function() {
validate();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="mark" name="mark">
<option value="">--</option>
<option value="bmw" data-price="200">bmw</option>
<option value="audi" data-price="400">audi</option>
</select>
<select id="series" name="series">
<option value="">--</option>
<option value="series-1" data-price="2000" >3 series</option>
<option value="series-1" data-price="3000" >5 series</option>
</select>
<div id="total"> </div>
I have 3 dropdowns every dropdown has 8 options. Now my goal is to limit the combined value of these 3 dropdowns to 8. So for example if you pick 7 in the first you can only select 1 in the next two if you select 1 in the second you can't select anything in the third.
I am trying to achieve my goal by disabling certain options, but there is a flaw in my logic. I can't change my selected option once I've selected one because I've disabled the options. Anyone knows how I can fix this problem?
Thanks in advance.
Here is a jsfiddle as example of my code:
https://jsfiddle.net/k7krx87L/4/
My jQuery code:
$(".options select").change(function() {
var value1 = $("#input_1_5").val();
var value2 = $("#input_1_6").val();
var value3 = $("#input_1_7").val();
var sum = parseInt(value1) + parseInt(value2) + parseInt(value3);
var rest = 9-sum;
$("#input_1_6 > option").slice(rest,9).each(function() {
$(this).attr("disabled", true);
});
var rest2 = rest - 9
$("#input_1_7 > option").slice(rest2,9).each(function() {
$(this).attr("disabled", true);
});
});
You need to have a variable check to see which items to be enabled like
var $selects = $(".options select").change(function() {
var sum = 0;
$selects.each(function() {
sum += +this.value;
});
var rem = 9 - sum;
$selects.each(function() {
var max = +this.value + rem;
$(this).find('option').prop('disabled', function() {
return +this.value > max;
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="options">
<select name="" id="input_1_5">
<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>
</select>
<select name="" id="input_1_6">
<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>
</select>
<select name="" id="input_1_7">
<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>
</select>
</div>
In your code you have to take ele from loop and it will work
$(".options select").change(function() {
var value1 = $("#input_1_5").val();
var value2 = $("#input_1_6").val();
var value3 = $("#input_1_7").val();
var sum = parseInt(value1) + parseInt(value2) + parseInt(value3);
var rest = 9-sum;
$("#input_1_6 > option").slice(rest,9).each(function(index, ele) {
$(ele).attr("disabled", true);
});
var rest2 = rest - 9
$("#input_1_7 > option").slice(rest2,9).each(function(index, ele) {
$(ele).attr("disabled", true);
});
});
I've three select-box here to choose Format, Amount & Shipping type. After selection, it will calculate price automatically.
here, how those select-box look like:
<p>Format: <select class="calculate" name="format">
<option value="0">Please Select</option>
<option value="0">Format 1</option>
<option value="0">Format 2</option>
</select></p>
<p>Amount: <select class="calculate" name="amount">
<option value="0">Select amount</option>
<option value="247">250pcs</option>
<option value="279">1,000pcs</option>
<option value="389">2,500pcs</option>
</select></p>
<p>Shipping type: <select id="surcharge" name="shipping">
<option value="0">Select Shipping</option>
<option value="10%">Standard</option>
<option value="15%">Express</option>
</select></p>
currently, the Amount for the both Format (Format 1/Format 2) are same.
what i'm trying to do is like: for the Format 1, the current Amount will remain same, but if user select Format 2 then the Amount will something like this:
<option value="0">Select amount</option>
<option value="300">250pcs</option>
<option value="350">1,000pcs</option>
<option value="400">2,500pcs</option>
where the value is different! how can i achive this?
here goes the JSfiddle
Thanks in advance for any help!
You should first set the new values in an array. So you can loop through them while changing the first select.
Then you can easily get the options from the 2nd select, and update them with the correct new values:
$(".calculate, #surcharge").on("change", function(){
if($(this).val() == 1)
{
var amountValues = new Array(0,250,400,500);
$("#menge option").each(function(key,value)
{
$(this).val(amountValues[key]);
});
} else if($(this).val() == 2)
{
var amount Values = new Array();
// .....
}
});
http://jsfiddle.net/7Bfk5/15/
You can do this by checking the text() in the options you are selecting
if ($('#sel option:selected').text() === 'Format 2') {
$('#amt option').each(function () {
alert($(this).text());
if ($(this).text() == "250pcs") $(this).val("300");
else if ($(this).text() == "1,000pcs") $(this).val("350");
else $(this).val("400");
});
}
working fiddle
You can create a function that does values/options replacement and call it on your select changes.
I did an example for you but used static html options to replace old ones, this might not be the best way but tried to keep it as simple as possible.
HTML
<p>Format: <select class="calculate format" name="format">
<option value="0">Please Select</option>
<option value="1">Format 1</option>
<option value="2">Format 2</option>
</select></p>
<p>Amount: <select class="calculate amount" name="menge">
<option value="0">Select Menge</option>
<option value="247">250pcs</option>
<option value="279">1,000pcs</option>
<option value="389">2,500pcs</option>
</select></p>
<p>Shipping type: <select id="surcharge" name="shipping">
<option value="0">Select Shipping</option>
<option value="10%">Standard</option>
<option value="15%">Express</option>
</select></p>
<p>Price: <span id="total">0 €</span></p>
Javascript
var updateValues = function (){
if($('.format').val() == 1) {
html = '<option value="300">300pcs</option>';
html += '<option value="400">400pcs</option>';
html += '<option value="500">500pcs</option>';
$('.amount').html(html);
} else if( $('.format').val() == 2) {
html = '<option value="600">600pcs</option>';
html += '<option value="900">900pcs</option>';
html += '<option value="1200">1200pcs</option>';
$('.amount').html(html);
}
};
$('.format').change(function(){updateValues()});
$(".calculate, #surcharge").on("change", function(){
var total = 0;
$('.calculate').each(function() {
if($(this).val() != 0) {
total += parseFloat($(this).val());
}
});
if($('#surcharge').val() != 0) {
total = total * ((100 + parseFloat($('#surcharge').val())) / 100);
}
$('#total').text(total.toFixed(2) + ' €');
});
Fiddle link
http://jsfiddle.net/7Bfk5/23/