How to calculate value from different selected dropdown ? I dont know how to show or set the value subTotal in the html or javascript.
For example, item1 will selected 2 and 1 so for the subtotal it will be 3 and the total at the end will be 3. But if the its selected 1 the total at the end will be 4.
Here my code
HTML:
<div class="class1">
<div class= "row">
<div class= "col">
<select class= "item1" onchange="update()">
<option name ="option" value="0">0</option>
<option name ="option" value="1">1</option>
<option name ="option" value="2">2</option>
</select>
</div>
</div>
<div class= "row">
<div class= "col">
<select class= "item1" onchange="update()">
<option name ="option" value="0">0</option>
<option name ="option" value="1">1</option>
<option name ="option" value="2">2</option>
</select>
</div>
</div>
<div class= "col">
<input name="subTotal1" id="subTotal1" type="text" readonly>
</div>
<div class= "row">
<div class= "col">
<select class= "item2" onchange="update()">
<option name ="option" value="0">0</option>
<option name ="option" value="1">1</option>
<option name ="option" value="2">2</option>
</select>
</div>
</div
<div class= "col">
<input name="subTotal2" id="subTotal2" type="text" readonly>
</div>
<div class= "col">
<input name="total" id="total" type="text" readonly>
</div>
</div
Javascript:
function update() {
var getAllItem1 = document.querySelectorAll(".item1");
var subTotal1 = 0;
getAllItem1.forEach(function(select) {
var valueItem1 = select.options[select.selectedIndex].value;
if (valueItem1 != 0) {
subtotal1 += parseInt(valueItem1);
}
});
document.getElementByID(".subTotal1").value = subtotal1;
}
You have a few things wrong here. Your variable subTotal1 is defined with a capital T, but when you reference it later, it is spelled subtotal1. That should be updated to match in all places referenced. Next you've used the getElementById method, but spelled it with a capital D. That should be lower case. You also left a . in front of the selector name subTotal1. An ID does not need this.
function update() {
var getAllItem1 = document.querySelectorAll(".item1");
var subTotal1 = 0;
getAllItem1.forEach(function(select) {
var valueItem1 = select.options[select.selectedIndex].value;
if (valueItem1 != 0) {
subTotal1 += parseInt(valueItem1);
}
});
document.getElementById("subTotal1").value = subTotal1;
}
And since you've tagged this as jQuery, but not used any, I've updated this using it:
function update()
{
var getAllItem1 = $(".item1");
var subTotal1 = 0;
$.each(getAllItem1, function(i, select) {
var v = $(select).val();
if (v != 0)
{
subTotal1 += parseInt(v);
}
});
$("#subTotal1").val(subTotal1);
}
$('select.item1').change(update)