【问题标题】:Wrote javascript to dynamically create table. Need help validating user input编写了 javascript 来动态创建表。需要帮助验证用户输入
【发布时间】:2017-10-29 05:59:15
【问题描述】:

我已经在 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>

【问题讨论】:

    标签: javascript validation dynamic html-table


    【解决方案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";
    }
    

    【讨论】:

    • 我知道怎么写代码。我对实际放置它的位置感到更加困惑。这会是一个嵌套的 if 语句吗?它是如何工作的?
    • 你可以把所有条件都放在一个 if 语句中,像这样if (rows is not a number, or rows &lt;= 0, or rows &gt;= 10, or cols is not a number, or cols is &lt;= 0, or cols is &gt;= 10) { render generic error message like "Rows and Columns must be positive numbers less than 10" } else { ... render table ... }
    猜你喜欢
    • 2011-03-08
    • 1970-01-01
    • 1970-01-01
    • 2020-10-29
    • 2014-07-10
    • 1970-01-01
    • 1970-01-01
    • 2012-03-18
    • 1970-01-01
    相关资源
    最近更新 更多