javascript - 使用 Javascript 将输入设置为只读

标签 javascript html

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

//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";
        }
    }
}
<!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>

最佳答案

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

此外,该属性是readOnly,而不是readonly

所以这个 scores[i].readonly="readonly"; 应该是 scores[i].readOnly="readonly";

创建了一个工作演示 here

关于javascript - 使用 Javascript 将输入设置为只读,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42510801/

相关文章:

javascript从外部作用域变量访问成员函数

javascript - 是否可以使用 jquery/javascript 加载 flash 播放器?

javascript - DailyMotion JS 在 iOS 上嵌入 API 和播放视频

javascript - 使用 JQuery 和 Javascript 获取 json 并解析它的最简单方法?

Python、Beautiful Soup、WebScraping、Pandas、Dataframe

javascript - 在 Bootstrap 中更改输入文本

javascript - 在异步函数中推送到数组不起作用

html - 使用 HTML5 Canvas 动画作为背景

javascript - 我需要从 jQuery 的最后一个元素中提取第二个的 ID

html - 我希望这些图像垂直对齐,我该如何实现?