Skip to content
Advertisement

If the input I put blank, then it will count 0

I am trying to put some amount, then it will show the calculation if all input will given any number, but I want, when I do not put anything in any one of that input, then the input will count “0” automatically..

<body>
    <input type='text' id='aaa'/>
    <input type='text' id='bbb'/>
    <input type='text' id='ccc'/>
    <input type='text' id='answer' name='ans' />
<form name ="testarea" Method="GET" Action="" id='form1'>
    <input type="button" onClick="Calculate();" value="calculate"/>
</form>
</body>
<script>


    function Calculate()
        {
        var aaa= document.getElementById('aaa').value;
        var bbb= document.getElementById('bbb').value;
        var ccc= document.getElementById('ccc').value; 
        var permin = parseFloat(aaa) * 82;
        var permin1 = parseFloat(bbb) * 40;
        var permin2 = parseFloat(ccc) * 10;
        var permin3=permin+permin1+permin2;
        document.getElementById('answer').value=permin3;
        document.form1.submit();
    }
</script>

Advertisement

Answer

    var aaa= document.getElementById('aaa').value;
    var bbb= document.getElementById('bbb').value;
    var ccc= document.getElementById('ccc').value; 
    var permin = (parseFloat(aaa)||0) * 82;
    var permin1 = (parseFloat(bbb)||0) * 40;
    var permin2 = (parseFloat(ccc)||0) * 10;
    var permin3=permin+permin1+permin2;
    document.getElementById('answer').value=permin3;

You can use the OR operator to replace NaN with 0 if parseFloat returns NaN.

You could shorten the upper code to:

 const ids = ["aaa","bbb","ccc"];
 const factors = [82,40,10];
 document.getElementById("answer").value = ids.reduce((count,id,index) => {
   const { value } = document.getElementById(id);
   return count + (parseFloat(value) || 0) * factors[index];
 }, 0);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement