表td的onkeyup函数添加输入验证?

时间:2015-10-21 13:03:08

标签: javascript

我正在处理一个数独项目并且被验证困扰,表格代码在整个过程中是相同的,所以除非需要更多代码,否则我会发布一小段代码。我想要做的是从我的数独中获取每个表数据单元格的值,并且onkeyup只允许1-9之间的数字。所有其他字符都会产生错误。到目前为止,我的javascript函数似乎没有得到任何值,我无法弄清楚原因。

    <table class="spuzzle">
    <thead>
    <tr><th></th>



        <th>1</th>
        <th>2</th>
        <th>3</th>
        <th>4</th>

        <th>5</th>
        <th>6</th>
        <th>7</th>


        <th>8</th>
        <th>9</th>

    </tr>
    </thead>
    <tbody>

     <tr>
    <th>A</th>
    <td class ="greenBox" rowspan="3" colspan="3">
        <table class="subTable">
            <tr>
                <td contenteditable="true" onkeyup="myFunction()"></td>
                <td contenteditable="true" onkeyup="myFunction()"></td>
                <td>4</td>


            </tr>
            <tr>
                <td contenteditable="true" onkeyup="myFunction()"></td>
                <td contenteditable="true" onkeyup="myFunction()"></td>
                <td contenteditable="true" onkeyup="myFunction()"></td>
            </tr>
            <tr>
                <td>3</td>
                <td>5</td>
                <td contenteditable="true" onkeyup="myFunction()"></td>
            </tr>
        </table>
    </td>


    function myFunction()
    {
    var num = document.getElementsByClassName("subTable").value;
    var num = parseInt(num, 10);
    alert(num);
    if(num < 1 || num > 9){
    document.getElementsByClassName("subTable").value = "";
    alert("Please Enter a Number Between 1 and 9.");
    }
    }

1 个答案:

答案 0 :(得分:1)

<强> Fiddle DEMO

我建议您将element传递给function parameter,然后点击innerHTML,如下所示:

更新了标记

<td contenteditable="true" onkeyup="myFunction(this)"></td><!-- Pass element with this-->
<td contenteditable="true" onkeyup="myFunction(this)"></td>
<td>4</td>

JS 然后会如下

function myFunction(ctrl)
{
    var num = ctrl.innerHTML; //get its innerHTML
    num = parseInt(num, 10);
    if(num < 1 || num > 9){
        ctrl.innerHTML="";//clear it if num is not what you expect
        alert("Please Enter a Number Between 1 and 9.");
    }
}

<强>更新

如果您想检查输入的字符是否为数字,请使用isNaN功能,如下所示:

function myFunction(ctrl)
{
    var num = ctrl.innerHTML;
    num = parseInt(num, 10);
    if(!isNaN(num))//if num is number then perform check for range
    {
        if(num < 1 || num > 9){
            ctrl.innerHTML="";
            alert("Please Enter a Number Between 1 and 9.");
        }
    }
    else
    {
        //just clear if any bad characters entered and show alert if needed
        ctrl.innerHTML="";
        alert('Please enter digits only');
    }
}

<强> UPDATED DEMO