簡體   English   中英

使用Javascript將輸入字段設置為只讀

[英]Setting input field readonly with Javascript

我正在通過另一個腳本動態設置 SecretAttribute 的值,但目前我很難將 Name 輸入字段設為readonly

嘗試通過 SecretAttribute 和 SecretElement 設置getElementByID ,但沒有骰子。

<input name="SecretAttribute" id="SecretAttribute" value="Y" type="checkbox" checked/> 
<html>
<head>
 <title>Demo Title</title>
<script type="text/javascript"> 
var SecretElement = document.getElementById('SecretAttribute');\
if (document.getElementById("SecretAttribute").checked;) {
    function DataCheck() {
    document.getElementById('Name').readOnly = true;
  } 
}

</script>
</head>
<body onload="DataCheck()">

  Demo6.1<br>
  Name: <input type="text" id="Name" name="Name"><br>

</body>
</html>

函數調用在 if 語句中。 將 if 條件放在調用中

 function DataCheck() { if(document.getElementById("SecretAttribute").checked) document.getElementById('Name').readOnly = true; } var SecretElement = document.getElementById('SecretAttribute');
 <input name="SecretAttribute" id="SecretAttribute" value="Y" type="checkbox" checked/> <html> <head> <title>Demo Title</title> </head> <body onload="DataCheck()"> Demo6.1<br> Name: <input type="text" id="Name" name="Name" value="You can't edit this"><br> </body> </html>

如果您使用較舊的瀏覽器,請嘗試使用setAttribute ,例如...

  var SecretElement = document.getElementById('SecretAttribute');
  if (SecretElement.checked) {
    document.getElementById('Name').setAttribute("readonly","readonly");
  }

暫無
暫無

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

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