Calculating a price with 4 select options - javascript

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>

Related

how to sum multiple select fields vlaues, including subtracting negative numbers (to zero)

I'm trying to use several select fields to modify a numeric starting point. The select fields contain some negative numbers, so I want to add/subtract accordingly. I currently cannot do this with JQuery - so I'm trying to figure out how in straight javascript. I've gotten this far, but it's only for a single select field. For the same reason, I'm not sure if the negative numbers are going to subtract:
<select class="select1 selectables" id="dropdown-1" name="dropdown1">
<option disabled="disabled" selected="selected" value="">select</option>
<option value="10">Choice 1 (plus 10)</option>
<option value="-5">Choice 2 (minus 5)</option>
<option value="60">Choice 3 (plus 60)</option>
</select>
<br />
<select class="select2 selectables" id="dropdown-2" name="dropdown2">
<option disabled="disabled" selected="selected" value="">select</option>
<option value="5">Choice A (plus 10)</option>
<option value="15">Choice B (minus 10)</option>
<option value="15">Choice C (plus 15)</option>
</select>
<br />
<select class="select3 selectables" id="dropdown-3" name="dropdown3">
<option disabled="disabled" selected="selected" value="">select</option>
<option value="5">Choice ii (- 35)</option>
<option value="15">Choice ii (plus 15)</option>
<option value="12">Choice iii (plus 12)</option>
</select>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var gg1 = new JustGage({
id: "gg1",
value: 0
// removed elements, as this area isn't an issue
});
document.getElementById('dropdown-1').addEventListener('change', (event) => {
sum = 0;
testvar = event.target.value;
if (testvar > 0) {
sum = (sum + testvar);
alert(`up ${testvar}`);
} else if (testvar < 1) {
sum = (sum - parseInt(testvar, 10));
alert(`down ${testvar}`);
}
gg1.refresh(sum);
return false;
});
</script>
You don't need special treatment for negative numbers. Simply add them as you would do with positive numbers. In the following snippet, I changed the values of negative options to their actual negative values. calculateSum() then calculates the sum from all boxes. Not just the changed one. Although an incremental version is definitely possible, there is no reason to do this with just three boxes. And this incremental variant is more likely to have bugs.
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementById('dropdown-1').addEventListener('change', calculateSum);
document.getElementById('dropdown-2').addEventListener('change', calculateSum);
document.getElementById('dropdown-3').addEventListener('change', calculateSum);
});
function calculateSum() {
sum = 0;
//iterate all three boxes
for (var i = 1; i <= 3; ++i) {
var box = document.getElementById('dropdown-' + i);
var value = parseInt(box.value);
if (!isNaN(value))
sum += value;
}
alert(sum);
return false;
}
<select class="select1 selectables" id="dropdown-1" name="dropdown1">
<option disabled="disabled" selected="selected" value="">select</option>
<option value="10">Choice 1 (plus 10)</option>
<option value="-5">Choice 2 (minus 5)</option>
<option value="60">Choice 3 (plus 60)</option>
</select>
<br />
<select class="select2 selectables" id="dropdown-2" name="dropdown2">
<option disabled="disabled" selected="selected" value="">select</option>
<option value="10">Choice A (plus 10)</option>
<option value="-10">Choice B (minus 10)</option>
<option value="15">Choice C (plus 15)</option>
</select>
<br />
<select class="select3 selectables" id="dropdown-3" name="dropdown3">
<option disabled="disabled" selected="selected" value="">select</option>
<option value="-35">Choice ii (- 35)</option>
<option value="15">Choice ii (plus 15)</option>
<option value="12">Choice iii (plus 12)</option>
</select>

how sum data attribute total price?

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>

HTML select option VALUE calculate

I am trying to make a simple "registry book" from a select HTML
The idea is 3 selecting options click confirm and based on the selected options make a price with a math formula or (don't know what is ) an array (in the sense of a table of like every var there) add a Hour:Minute from machine and place it in a paragraph.
It will work. (just learning HTML and CSS)
Math would be select2 * select3 with one exception in the case of [select2(option1 and option2) * select3 = samevalue)
With that aside can someone post a modular simplistic type of code that would Help.
For those who need to read some more:(copy&paste* - *Sorry for indentation)
document.getElementById("Confirm").onClick = function() {
var entry = ""
document.getElementById("Televizor").onChange = function() {
if (this.selectedIndex !== 0) {
entry += this.value;
}
};
document.getElementById("Controllere").onChange = function() {
if (this.selectedIndex !== 0) {
entry += this.value;
}
};
document.getElementById("Timp").onChange = function() {
if (this.selectedIndex !== 0) {
entry += this.value;
}
};
document.getElementById("Table").innerHTML = "<br> " + entry + Date();
var entry = ""
}
<h2>TV-uri</h2>
<button type="button" onclick="document.getElementById('demo').innerHTML = Date()">Date & Time.</button>
<p id="demo">Dunno</p>
<div class="container">
<select id="Televizoare">
<option value="0">Televizoare</option>
<option value="1">Tv 1</option>
<option value="2">Tv 2</option>
<option value="3">TV 3</option>
<option value="4">Tv 4</option>
<option value="5">TV 5</option>
<option value="6">Tv 6</option>
<option value="7">TV 7</option>
</select>
<select id="Controller">
<option value="0">Controllere</option>
<option value="1c">1 Controller</option>
<option value="2c">2 Controllere</option>
<option value="3c">3 Controllere</option>
<option value="4c">4 Controllere</option>
</select>
<select id="Timp">
<option value="0">Timp</option>
<option value="1h">1 ora</option>
<option value="1h2">1 ora 30 minute</option>
<option value="2h">2 ore</option>
<option value="2h2">2 ore 30 minute</option>
<option value="3h">3 ore</option>
</select>
<button id="Confirm" onclick="Confrim)">Confirm</button>
</div>
<p id="Table"></p>
Well, you could start off by making sure the spelling and capitalization of your IDs and function names match.
Also, you should create some form of a validation method to check if all the fields are valid before proceeding to the calculation method.
Not sure what you are multiplying, but if you can at least get the valuse from the form fields, that's half the battle.
You should also enclose all your fields within a form object so you can natively interact with the form in a traditional HTML fashion.
// Define the confirm clicke listener for the Confirm button.
function confirm() {
// Grab all the fields and apply them to a map.
var fields = {
'Televizoare' : document.getElementById('Televizoare'),
'Controllere' : document.getElementById('Controllere'),
'Timp' : document.getElementById('Timp')
};
// Determine if the user selected an option for all fields.
var isValid = doValidation(fields);
if (!isValid) {
document.getElementById("Table").innerHTML = 'Please provide all fields!';
return;
}
// Create listeners ???
fields["Televizoare"].onChange = function(e) { };
fields["Controllere"].onChange = function(e) { };
fields["Timp"].onChange = function(e) { };
// Set the value of the paragraph to the selected values.
document.getElementById("Table").innerHTML = Object.keys(fields)
.map(field => fields[field].value)
.join(' — ');
}
// Validation function to check if ALL fields have options selected other than 0.
function doValidation(fields) {
return [].every.call(Object.keys(fields), field => fields[field].selectedIndex !== 0);
}
<h2>TV-uri</h2>
<button type="button" onclick="document.getElementById('demo').innerHTML = Date()">Date & Time.</button>
<p id="demo">Dunno</p>
<div class="container">
<select id="Televizoare">
<option value="0">Televizoare</option>
<option value="1">Tv 1</option>
<option value="2">Tv 2</option>
<option value="3">TV 3</option>
<option value="4">Tv 4</option>
<option value="5">TV 5</option>
<option value="6">Tv 6</option>
<option value="7">TV 7</option>
</select>
<select id="Controllere">
<option value="0">Controllere</option>
<option value="1c">1 Controllere</option>
<option value="2c">2 Controllere</option>
<option value="3c">3 Controllere</option>
<option value="4c">4 Controllere</option>
</select>
<select id="Timp">
<option value="0">Timp</option>
<option value="1h">1 ora</option>
<option value="1h2">1 ora 30 minute</option>
<option value="2h">2 ore</option>
<option value="2h2">2 ore 30 minute</option>
<option value="3h">3 ore</option>
</select>
<button id="Confirm" onclick="confirm()">Confirm</button>
</div>
<p id="Table"></p>

Note able to set count on dropdown change

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>

Other radio buttons not clickable after using Javascript function to select certain Radio based on if statement

I am working on a car service reservation system and there are three different vehicle options. I am trying to code it to where if there are a certain number of passengers listed, the vehicle automatically switches to something that accommodates more people and disables the first vehicle.
I have accomplished this but there are problems. I'm using arrays and functions to define the amount of passengers. I am then using a variable that adds the values these functions spit out to create a total number of passengers. Then I have set up an if statement to say if the value is greater than four, change to this radio input and disable the first one.
The problem occurs when this happens I am no longer able to select the third vehicle option and I don't know why.
I also attempted to set the total passenger value to where if it is less than five, the first vehicle is automatically selected. This did not work either.
Ultimately I would like it to act in such a way that if over 14 passengers are selected, the user receives an error (this is working fine). If less than 5 passengers are selected, the first vehicle is selected. If over 4 passengers are selected, the second vehicle is selected and the third is still an option. If more than 8 passengers are selected, both the first and third vehicle are disabled.
Hopefully my code is not overly ill formatted. I am fairly new to Javascript and have been piecing tutorials together. Here is a jsfiddle of the part of the form that is not working.
Here is the Javascript code:
var adults_teenagers2 = new Array();
adults_teenagers2["1"] = 1;
adults_teenagers2["2"] = 2;
adults_teenagers2["3"] = 3;
adults_teenagers2["4"] = 4;
adults_teenagers2["5"] = 5;
adults_teenagers2["6"] = 6;
adults_teenagers2["7"] = 7;
adults_teenagers2["8"] = 8;
adults_teenagers2["9"] = 9;
adults_teenagers2["10"] = 10;
adults_teenagers2["11"] = 11;
adults_teenagers2["12"] = 12;
adults_teenagers2["13"] = 13;
adults_teenagers2["14"] = 14;
function AmountAdultsTeenagers() {
var AdultsTeenagersNumberAmount = 0;
var theForm = document.forms["resForm"];
var AdultsTeenagersNumber = theForm.elements["adults_teenagers"];
AdultsTeenagersNumberAmount = adults_teenagers2[AdultsTeenagersNumber.value];
return AdultsTeenagersNumberAmount;
}
var children2 = new Array();
children2["0"] = 0;
children2["1"] = 1;
children2["2"] = 2;
children2["3"] = 3;
children2["4"] = 4;
children2["5"] = 5;
children2["6"] = 6;
children2["7"] = 7;
children2["8"] = 8;
function Amountchildren() {
var childrenNumberAmount = 0;
var theForm = document.forms["resForm"];
var childrenNumber = theForm.elements["children"];
childrenNumberAmount = children2[childrenNumber.value];
return childrenNumberAmount;
}
var infants2 = new Array();
infants2["0"] = 0;
infants2["1"] = 1;
infants2["2"] = 2;
infants2["3"] = 3;
infants2["4"] = 4;
infants2["5"] = 5;
infants2["6"] = 6;
infants2["7"] = 7;
infants2["8"] = 8;
function Amountinfants() {
var infantsNumberAmount = 0;
var theForm = document.forms["resForm"];
var infantsNumber = theForm.elements["infants"];
infantsNumberAmount = infants2[infantsNumber.value];
return infantsNumberAmount;
}
function calculateTotal() {
var over = AmountAdultsTeenagers() + Amountchildren() + Amountinfants();
if(over>'14')
{
alert('Sorry, no vehicle can accomodate more than 14 passengers.');
document.getElementById("firstPageSubmit").disabled = true;
}
else {
document.getElementById("firstPageSubmit").disabled = false;
}
if(over<'5') {
document.getElementById("towncar").checked = true;
}
if(over>'4')
{
document.getElementById("towncar").disabled = true;
document.getElementById("stretch_limousine").disabled = false;
document.getElementById("passenger_van").checked = true;
}
else {document.getElementById("towncar").disabled = false;
}
}
and the HTML:
<form method="post" class="res_form" id="resForm" name="res_form" onSubmit="return quoteCheck();">
<ul>
<li id="steps">Step 1 of 3 - Select Type of Service/Get Quote</li>
<li class="form_notice"><span>Reservations must be at least 48 hrs prior for towncars and 72 hrs for any other vehicle.</span></li>
<li><fieldset class="res_form_fs" id="passengers">
<legend>Passengers:</legend>
<label for="adults_teenagers" class="selectLabel">Adults/Teenagers:
<select name="adults_teenagers" id="adults_teenagers" onchange="calculateTotal()">
<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>
</select></label>
<label for="children" class="selectLabel">Children:
<select name="children" id="children" onchange="calculateTotal()">
<option value="0">None</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></label>
<label for="infants" class="selectLabel">Infants:
<select name="infants" id="infants" onchange="calculateTotal()">
<option value="0">None</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></label>
</fieldset>
</li>
<li>
<fieldset class="res_form_fs">
<legend>Select Vehicle:</legend>
<p class="radioT"><input type="radio" value="Towncar" onclick="calculateTotal()" name="vehicle" id="towncar" class="radio" unchecked /></p><p class="nonradioT"><span class="radioOption"><label for="towncar">Towncar</label></span></p><br />
<p class="radioT"><input type="radio" value="Passenger Van" onclick="calculateTotal()" name="vehicle" id="passenger_van" class="radio" unchecked /></p><p class="nonradioT"><span class="radioOption"><label for="passenger_van">Passenger Van</label></span></p><br />
<p class="radioT"><input type="radio" value="Stretch Limousine" onclick="calculateTotal()" name="vehicle" id="stretch_limousine" class="radio" unchecked /></p><p class="nonradioT"><span class="radioOption"><label for="stretch_limousine">Stretch Limousine</label></span></p>
</fieldset>
</li>
<li><input name="submit" type="submit" id="firstPageSubmit" class="ressubmitButton" value="Continue to Make Reservation" /></li>
</ul>
</form>
Here i change name all select option as same and now it's work. Please see in below JSFiddle:
<select name="adults_teenagers">
http://jsfiddle.net/ketan156/cthbg27h/8/
edit:
change in if condition: following is new JSFiddle:
http://jsfiddle.net/ketan156/cthbg27h/10/
is is ok? as per my understanding you like to get it.
As You need i edited JSFiddle:
http://jsfiddle.net/ketan156/cthbg27h/11/

Categories