表 - 表中的Javascript和数学

时间:2014-08-16 15:12:27

标签: javascript html5

我是HTML5和CSS3的新手。

1)我想帮助找出表格。我希望用户将值(info1,info2,info3)输入到表列中。然后在“单击”按钮上使用这些值,在“答案”列中生成答案(答案)。

2)另外,如何仅将输入值限制为数值?我尝试使用输入类型=“数字”,但得到小箭头来增加值,但我仍然可以输入字母。

由于 CzY马

代码:

<!DOCTYPE html>

<html>
<head>
    <title>Table</title>
    <script type="text/javascript" >
    function sayHi(){
        var info1 = parseInt(document.getElementById("info1").value) ;
        var info2 = parseInt(document.getElementById("info2").value) ;
        var info3 = parseInt(document.getElementById("info3").value) ;

        var Answer = document.getElementById("Answer");
        answer.value = info1.value + info2.value * info3.value /100 ;
    } // end sayHi

</script>    
</head>

<body>
<table>
    <tr>
        <th>Row 1</th>
        <th>Row 2</th>
        <th>Row 3</th>
        <th>Answer</th>
    </tr>

    <tr>
        <td><input type = "text"
            id = "info1">
        </td>
        <td><input type = "text"
            id = "info2">
        </td>
        <td><input type = "text"
            id = "info3">
        </td>
        <td><input type = "text"
            id = "Answer" READONLY>
        </td>

    </tr>





   </table>
<section>
            <input type = "button"
            value = "Calculate"
            onClick = "javascript:sayHi()"/>
</section>

</body>
</html>

3 个答案:

答案 0 :(得分:0)

我建议检查解析的数字是否为NaN。如果是这样,用户输入的内容无法解析为数字。

if (isNaN(info1) || isNaN(info2) || isNaN(info3)) {
    alert('Only numbers!');
    return false;
}

另外,因为您已经将文本字段的值解析为数字,所以在JavaScript中使用变量时无需添加.value

Answer.value = info1 + info2...

答案 1 :(得分:0)

尝试使用此oneliner创建计算值:

( [].slice.call( 
   document.querySelectorAll('table td input[type=text]:not([disabled])'))
    .map( function (a) { return +(a.value) || 0; })
    .reverse()
    .reduce( function (a,b,i) {return i<2 ? a*b : a+b;} ) ) / 100

有了它,输入值会自动检查(+a.value || 0):如果不是数字,则使用默认值0。

jsFiddle

中的演示

请参阅thisArray.map)和thisArray.reduce

答案 2 :(得分:0)

你的代码中有各种错误和错误,列出的内容太多了,但这是一个小提琴试试看,你可以看到你的固定代码正常工作

http://jsfiddle.net/bz7hknhk/

sayHi = function () {
 var info1 = parseInt(document.getElementById("info1").value);
 var info2 = parseInt(document.getElementById("info2").value);
 var info3 = parseInt(document.getElementById("info3").value);

 var Answer = document.getElementById("Answer");
 Answer.value = info1 + info2 * info3 / 100;
} // end sayHi