Javascript文本框作为字符串收到

时间:2012-12-07 13:47:19

标签: javascript html

这是我使用的Html表单。

<form name="calculate" method="get" action="#" onsubmit="return Validate()">
<label>Enter a number</label>
<input id="numb1" name="numb1" id="numb2" placeholder="Number 1">

<label>Enter another number</label>
<input id="numb2" name="numb2" id="numb2" placeholder="Number 2">

<label>Result</label>
<textarea style="text-align:center; height:85px; max-height:85px;" name="summ" id="summ" disabled="disabled" placeholder="Result" dir="ltr"></textarea>
<br />
<input id="calc" name="calc" type="submit" value="Calculate!">

JS

    function Validate() {
        if (calculate.numb1.value == "" || calculate.numb2.value == "") {
            alert("Check the form again");
            calculate.numb1.focus();
            document.getElementById('summ').value = "";
            return (false);
        }
        Update()
        return (true);

    }
    function Update() {
        var plus = calculate.numb1.value + calculate.numb2.value;
        var minus = calculate.numb1.value - calculate.numb2.value;
        var mult = calculate.numb1.value * calculate.numb2.value;
        var div = calculate.numb1.value / calculate.numb2.value;

        var multi = document.getElementById("summ").value = calculate.numb1.value + "+" + calculate.numb2.value + "=" + plus + "\n" + calculate.numb1.value + "-" + calculate.numb2.value + "=" + minus + "\n" + calculate.numb1.value + "*" + calculate.numb2.value + "=" + mult + "\n" + calculate.numb1.value + "/" + calculate.numb2.value + "=" + div;
    }

所有计算工作都完全接受Plus功能。 当你输入4 + 4例如你得到44 ... 我尝试了parseFloat,但仍然没有任何变化。

2 个答案:

答案 0 :(得分:0)

var numb1 = parseFloat(document.calculate.numb1.value);
var numb2 = parseFloat(document.calculate.numb2.value);

var plus = numb1 + numb2;
var minus = numb1 - numb2;
var mult = numb1 * numb2;
var div = numb1 / numb2;

答案 1 :(得分:0)

首先将它们转换为数字。 使用字符串值对每个计算执行此操作。

var plus = Number(calculate.numb1.value) + Number(calculate.numb2.value);

列昂