luka gab luka gab - 8 months ago 40
HTML Question

HTML form with branch conditions not working

I want to create a form where the user enters a value, checks a radio button and then clicks on the submit button. The user should get a response by an alert message in the following three cases.

Case 1: Expressed checked AND Product quantity is > 50 && < 500

Case 2: Expressed checked AND Product quantity is NOT > 50 && < 500

Case 3: Standard checked

Regardless of whatever value I enter, it goes straight to Case 2.
Case 1 and Case 3 are never reached.

Code Snippet

<!DOCTYPE html>
<title>HTML form</title>
function calculate() {
var productQuantity = document.getElementById("product-quantity").value +
" Units";
var express = document.getElementById("express");
var standard = document.getElementById("standard");

// EXPRESSED ------------------------------
if (express.checked) {
if ((productQuantity > 50) && (productQuantity < 500)) {
// CASE 1
alert("your order of " + productQuantity +
" will be ready within two working day");
} else {
// CASE 2
alert("sorry! your order is " + productQuantity +
" and it has to be over 50 in order to qualify for this service"
// STANDARD ------------------------------
else if (standard.checked) {
// CASE 3
alert("your order of " + productQuantity +
" will be ready within seven working day");
<div class="container">
<div class="row" style="padding-top:20px">
<div class="col-md-6">
<div class="input-group">
<label for="product-quantity">Please Enter number of units
for this product:</label> <input class="form-control" id=
"product-quantity" placeholder="Product Quantity" type=
<div id="product-time" style="padding-top:20px">
<label for="title">Production Time</label>
<div class="row">
<div class="col-md-3 col-sm-6">
<input id="express" name="radio" type="radio"> <label for=
<div class="col-md-3 col-sm-6">
<input id="standard" name="radio" type="radio"> <label for=
</div><span class="input-group-btn" style=
"padding-top:25px"><button class="btn btn-default" id="button" onclick=
"calculate()" type="button"><span class="input-group-btn" style=


productQuantity is a string, comparing it to an integer in your if statement will always be false. I would recommend converting it to an integer before your if statement, then converting it back to a string and adding the ' Units' part.

var productQuantity = document.getElementById("product-quantity").value
var productQuantityInt = parseInt(productQuantity, 10);
if (productQuantityInt > 50 && productQuantityInt < 500){...};
productQuantity += ' Units';

Hope that helps

Edit (oops):

Since the productQuantity input field is set as a 'number' type, you don't need a lot of my code. This should work:

var productQuantity = document.getElementById("product-quantity").value
if (productQuantity > 50 && productQuantity < 500){...};
productQuantity += ' Units';