2017-02-28 16 views
0

我试图使用Javascript将输入字段设置为只读,如果它们不包含任何值,即如果它们为null。这是我的代码,我没有从调试器接收到任何错误,但它只是拒绝工作,可能有人使用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>

+0

应该是'readOnly' – epascarello

+0

'得分[I] .readonly =“只读“;' - 只读DOM属性是一个布尔值。它可以具有“真”和“假”的值。 ''readonly''只能工作,因为字符串被转换为布尔值。作为@Quentin提到的 – Quentin

+0

,关于[这里](https://www.w3schools.com/jsref/prop_text_readonly.asp)它是scores [i] .readOnly = true; –

回答

1

首先,您的HTML中没有编号为score_row1的元素,所以您的js会抛出错误并失败。

也是该酒店是readOnly而不是readonly

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

成立了工作演示here

+0

非常感谢,现在开始工作 – MGS

1

文本输入的值将始终是串。

如果没有输入任何内容,则值将是""。它永远不会是null

+0

指出,但我试图实现的是将输入设置为只读。因为没有任何值等于null,这应该意味着所有的输入字段将被设置为只读,但情况并非如此 – MGS

相关问题