簡體   English   中英

使用Javascript將輸入設置為只讀

[英]Using Javascript to set input to readonly

我試圖使用Javascript將輸入字段設置為只讀(如果它們不包含任何值),即如果它們為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"; } } } 
 <!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> 

文本輸入的值將始終為字符串。

如果未輸入任何內容,則該值為"" 它永遠不會為null

首先,您的HTML中沒有ID為score_row1元素,因此您的js將拋出錯誤並失敗。

此外,該屬性為readOnly而非readonly

因此,這scores[i].readonly="readonly"; 應該是scores[i].readOnly="readonly";

在這里創建了一個工作演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM