Search code examples
javascripthtmlmathcalculatordivide

HTML/Javascript Calculation


I need to create a form of calculator, where the user inputs their information to get the result.

I need 3 numbers, each in a seperate field, to be added together and then subtracted from 6000 via a submit button. The result will appear in a fourth field, text read only.

Then (this is the part I can't seem to find) the number created in that fourth field will be subtracted from 2000 and divided by 3, the result appearing in a fifth field. Makes sense? Here is more of a breakdown:


One: ###
Two: ###
Three: ###

Four (6000-(one+two+three)): ###
Five ((2000-four)/3): ###


Here is some code I have already:

One &nbsp;<input name=text type=text value=0><br>
Two &nbsp;<input name=text type=text value=0><br>
Three &nbsp;<input name=text type=text value=0><br><br>
<input type=button value="Calculate" onclick="subtract()"><br><br>

Four <br><br><input name=sum id=sum type=text readonly></font>

<script language=javascript>
function subtract() {
var sum =6000;
var valid = true;
var inputs = document.getElementsByName( 'text');
for(i =0; i < inputs.length; i++) {
if( inputs[i].value.match( /^[0]*(\d+)$/)) {
sum -= parseInt(RegExp.$1);
}
else {valid=false;}
}
if(valid) {
document.getElementById( 'sum').value = sum;
}
else{
alert("Please enter numbers only");
}
}
</script>

Any help is much appreciated!


Solution

  • It might work like this:

    One &nbsp;<input name=text type=text value=0><br>
    Two &nbsp;<input name=text type=text value=0><br>
    Three &nbsp;<input name=text type=text value=0><br><br>
    <input type=button value="Calculate" onclick="subtract()"><br><br>
    
    Four <br><br><input name=sum id=sum type=text readonly><br>
    
    Five <br><br><input name=five id=five type=text readonly><br>
    
    <script language=javascript>
    function subtract() {
        var sum =6000;
        var valid = true;
        var inputs = document.getElementsByName( 'text');
        for(i =0; i < inputs.length; i++) {
            if( inputs[i].value.match( /^[0]*(\d+)$/)) {
            sum -= parseInt(RegExp.$1);
            }
            else {valid=false;}
        }
        if(valid) {
            document.getElementById('sum').value = sum;
            document.getElementById('five').value = ((2000-sum)/3);
        } else{
            alert("Please enter numbers only");
        }
    }
    </script>
    

    Live demo