'Conditional Statement With Decimal & Number Comparison in Javascript
btn.addEventListener("click", updateResult);
function updateResult(){
chked = document.querySelectorAll('input[type="checkbox"]:checked').length;
array = [];
var checkboxes = document.querySelectorAll('input[type=checkbox]:checked')
for (var i = 0; i < checkboxes.length; i++) {
array.push(checkboxes[i].value)
}
sum = 0;
for (var e = 0; e < array.length; e++) {
sum += Number(array[e]);
}
total = sum + chked;
if (total < 7) {
result = "Low";
}
else if (total > 14) {
result = "High";
}
else {
result = "Moderate";
}
document.getElementById("p").innerHTML = "";
document.getElementById("p").textContent += total + " " + result;
}
<input type="checkbox" value="5"/> Value (5)
<br/>
<input type="checkbox" value="2"/> Value (2)
<br/>
<input type="checkbox" value="2.5"/> Value (2.5)
<br/>
<input type="checkbox" value="38"/> Value (38)
<br/>
<input type="checkbox" value="7.5"/> Value (7.5)
<br/>
<input type="checkbox" value="2.3"/> Value (2.3)
<br/><br/>
<button Id="btn">Update</button>
<br/>
<p id="p"></p>
I have a form where I am taking the sum of the total number of boxes checked plus the total value associated with the checked box. The values frequently have decimals (ie 2.5).
I am developing this on a Elementor for WP form using html for the checkbox list and Javascript to generate the result. The result does show correctly on the actual page; however, when the result is emailed out it keeps defaulting to the else statement.
I tried using parseFloat on the <> comparison with no change in the outcome. I'm not super versed in JS and at a complete loss at this point, any help is greatly appreciated.
chked = document.querySelectorAll('input[type="checkbox"]:checked').length;
array = [];
var checkboxes = document.querySelectorAll('input[type=checkbox]:checked')
for (var i = 0; i < checkboxes.length; i++) {
array.push(checkboxes[i].value)
}
sum = 0;
for (var e = 0; e < array.length; e++) {
sum += Number(array[e]);
}
total = sum + chked;
result = " ";
if(total < 7)
{
result = "Low";
}
else if(total > 14)
{
result = "High";
}
else {
result = "Moderate";
}
return result;
Solution 1:[1]
Thanks guys, I figured it out. Barmar got me to thinking... it is a multi-step form and I have a checkbox on the last step for accepting the Terms of Use. That was the issue. Face palm moment for me, appreciate the assist.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Faron |
