写了javascript来动态创建表。需要帮助验证用户输入

时间:2013-02-14 01:04:44

标签: javascript validation dynamic html-table

我已经在javascript中创建了一个表。它基于用户输入,并将检查以确保输入的值是一个数字。但我如何检查以确保输入的值是 高于0 并且不到10

<html>
<head>
    <title>Homework 1</title>

    <script language="javascript" type="text/javascript">
    function doWork(){
    var rows = document.getElementById("input1").value;
    var columns = document.getElementById("input2").value;
    //alert(rows);
    //alert(columns);
    if(isNaN(rows) == true || isNaN(columns) == true){
        document.getElementById('tablePlacement').innerHTML = "Input must be integer";
    }
    else{
    var htmlInput = "";
    htmlInput += "<table border='1'>";
    htmlInput += "<tr>";

    //Column Headers
    for (i = 0; i <= columns; i++){
        htmlInput += ("<td><b>" + i + "</b></td>");
    }
    htmlInput += "</tr>";
    for (i = 1; i <= rows; i++){
        htmlInput += ("</br><tr><td><b>" + i + "</b></td>");

        for (j = 1; j<= columns; j++){
            var multiplyResult = i * j;
            htmlInput += ("<td>" + multiplyResult + "</td>");
        }
        htmlInput += "</tr>";
    }
    htmlInput += "</table>";
    document.getElementById('tablePlacement').innerHTML = htmlInput;
    }

    };
    </script>
</head>
<body>
    <form id="input1Form">
        Rows: <input type="text" id="input1">
    </form>
    <form id="input2Form">
        Columns: <input type="text" id="input2">
    </form>
    <button type="button" onclick="doWork()">Enter</button>
    <div id="tablePlacement">
    </div>
</body>

1 个答案:

答案 0 :(得分:1)

 if(rows <=0 || rows >= 10){
    document.getElementById('tablePlacement').innerHTML = "Input rows must be between 1 and 9";
}

 if(cols <=0 || cols >= 10){
    document.getElementById('tablePlacement').innerHTML = "Input cols must be between 1 and 9";
}