Javascript calculations holding variables

2019-06-11 14:41发布

问题:

I'm exercising in javascript and i've made this script in order to calculate the sum of 2 variables and then use this sum in a third equation! any thoughts on how to make this work will be very useful!

<form name="Calcultor" Method="Get" id='form1'>First Number:
    <input type="text" name="fnum" size="35" id="first">+ Second Number:
    <input type="text" name="snum" size="35" id="sec">
    <br>
    <br>Answer:
    <input type="text" name="ans" size="35" id="ans" />
    <input type="text" name="ans2" size="35" id="ans2" />
    <button type="button" onclick="Calculate();">Calculate</button>
</form>
<script lang="javascript">
    function Calculate() {
        var first = document.getElementById('first').value;
        var sec = document.getElementById('sec').value;
	var ans = document.getElementById('ans').value;

        document.getElementById('ans').value = parseInt(first) + parseInt(sec);
	document.getElementById('ans2').value = parseInt(ans);
        document.form1.submit();
    }
</script>

Thanks in advance!

回答1:

Here it is:

function Calculate() {
    var first = document.getElementById('first').value;
    var sec = document.getElementById('sec').value;
    var ans = document.getElementById('ans').value;

    document.getElementById('ans').value = parseInt(first) + parseInt(sec);
    document.getElementById('ans2').value = document.getElementById('ans').value;
    /*document.form1.submit();*/
}
<form name="Calcultor" Method="Get" id='form1'>First Number:
    <input type="text" name="fnum" size="35" id="first">+ Second Number:
    <input type="text" name="snum" size="35" id="sec">
    <br>
    <br>Answer:
    <input type="text" name="ans" size="35" id="ans" />
    <input type="text" name="ans2" size="35" id="ans2" />
    <button type="button" onclick="Calculate();">Calculate</button>
</form>

Feel free to ask, if anything isn't clear!

Update (increment last input value by one):

function Calculate() {
    var first = document.getElementById('first').value;
    var sec = document.getElementById('sec').value;
    var ans = document.getElementById('ans').value;

    document.getElementById('ans').value = parseInt(first) + parseInt(sec);
    document.getElementById('ans2').value = parseInt(document.getElementById('ans').value) + 1;
    /*document.form1.submit();*/
}
<form name="Calcultor" Method="Get" id='form1'>First Number:
    <input type="text" name="fnum" size="35" id="first">+ Second Number:
    <input type="text" name="snum" size="35" id="sec">
    <br>
    <br>Answer:
    <input type="text" name="ans" size="35" id="ans" />
    <input type="text" name="ans2" size="35" id="ans2" />
    <button type="button" onclick="Calculate();">Calculate</button>
</form>

You should use parseInt() before summing numbers, without parsed value you are summing string with number, and as expected, the result will be a string with one more character.