使用Javascript将输入设置为只读

时间:2017-02-28 14:02:04

标签: javascript html

我尝试使用Javascript将输入字段设置为readonly,如果它们不包含任何值,即它们为null。这是我的代码,我没有从调试器收到任何错误,但它只是拒绝工作,可能有人



//checkScore();
function checkScore(){
    document.getElementById('score_row1').readonly = true;
    var scores = document.getElementsByClassName("score_holder");
    var i;
    for(i=0; i<scores.length; i++){
        if(scores[i].value!=null){
            scores[i].readonly="readonly";
        }
    }
}
&#13;
<!doctype html>
<html>
    <head>
    </head>

    <body onload="checkScore()">


        <table align="center" cellpadding="3">
            <tr valign="baseline">
                <td colspan="3" align="center" id="course_row25" value="EDU-101"><strong>EDUCATION COURSES</strong></td>
            </tr>
            <tr>
                <td align="right">
                    <input name="course_row1" type="text" id="course_row1" title="EDU-101: Historical Foundation of Education" value="EDU-101" size="5" readonly="readonly" />
                </td>
                <td>&nbsp;</td>
                <td>
                    <input type="text" value="30" size="5" class="score_holder" />
                </td>
            </tr>
            <tr>
                <td align="right" id="course_row1" name="course_row1" value="EDU-101">
                    <input name="course_row1" type="text" id="course_row1" title="EDU-101: Historical Foundation of Education" value="EDU-101" size="5" readonly="readonly" />
                </td>
                <td>&nbsp;</td>
                <td>
                    <input type="text" size="5" class="score_holder" />
                </td>
            </tr>
            <tr>
                <td align="right" id="course_row1" name="course_row1" value="EDU-101">
                    <input name="course_row1" type="text" id="course_row1" title="EDU-101: Historical Foundation of Education" value="EDU-101" size="5" readonly="readonly" />
                </td>
                <td>&nbsp;</td>
                <td>
                    <input type="text" value="10" size="5" class="score_holder" />
                </td>
            </tr>

        </table>
    </body>
</html>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

文字输入的值始终为字符串。

如果未输入任何内容,则值为""。永远不会是null

答案 1 :(得分:1)

首先,HTML中没有id为score_row1的元素,因此你的js会抛出错误并失败。

该属性也是readOnly而不是readonly

因此scores[i].readonly="readonly";应为scores[i].readOnly="readonly";

创建了一个有效的演示here

相关问题