luka gab luka gab - 6 months ago 14
HTML Question

radio button with input condition

I wanted to create a form where it take value from the user and the check a radio button and once submit it gives a value if it meets all condition, here is my code:

<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 type="number" class="form-control" id="product-quantity" placeholder="Product Quantity">

</div>
</div>
</div>



<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 type="radio" name="radio" id="express"/> <label for="productionTime"> Express </label>
</div>
<div class="col-md-3 col-sm-6">
<input type="radio" name="radio" id="standard" /> <label for="productionTime"> Standard </label>
</div>
</div>
</div>


<span class="input-group-btn" style="padding-top:25px">
<button class="btn btn-default" type="button" id="button" onclick="calculate()">Submit!</button>
</span>

</div>


javascript:

<script>

function calculate(){
var productQuantity = document.getElementById("product-quantity").value + " Units";

var express = document.getElementById("express");
var standard = document.getElementById("standard");
if(express.checked){


if(productQuantity > 50 && productQuantity <500){
alert("your order of " + productQuantity+ " will be ready within two working day")
}
else {
alert("sorry! your order is " + productQuantity +" and it has to be over 50 in order to qualify for this service")
}
}
else if(standard.checked){
alert("your order of " + productQuantity+ " will be ready within seven working day")
}



}




whatever value i enter it goes straight to else condition.

Answer

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';
Comments