簡體   English   中英

如何使輸入字段為只讀

[英]How to make an input field readonly

我想使輸入字段為只讀。 下面的代碼為我工作。 但是,如果刷新頁面,則輸入字段將變為只讀,並且我無法在輸入字段中輸入任何內容。 我希望只有在輸入字段中存在數據后,它才能變為只讀。

      const disableInputs = function() {
      sessionStorage.disableInputs = 'true';
      document.getElementById('firstname').disabled = true;
      document.getElementById('lastname').disabled = true;
      document.getElementById('email').disabled = true;
      document.getElementById('mew').disabled = true;
      };
      if (sessionStorage.disableInputs === 'true') disableInputs();
      document.getElementById('myButton').onclick = disableInputs;

非常感謝您的幫助。謝謝

使用此document.getElementById("your-id").readOnly = true;document.getElementById("your-id").readOnly = true;

資料來源: https : //www.w3schools.com/jsref/prop_text_readonly.asp

w3schools的代碼段: https ://www.w3schools.com/jsref/tryit.asp ? filename = tryjsref_text_readonly2

 function myFunction() { document.getElementById("myText").readOnly = true; } 
 <!DOCTYPE html> <html> <body> Name: <input type="text" id="myText"> <p>Click the button to set the text field to read-only.</p> <p><strong>Tip:</strong> To see the effect, try to type something in the text field before and after clicking the button.</p> <button onclick="myFunction()">Try it</button> </body> </html> 

在HTML中:

<input type="text" id="someid" name="somename" readonly="readonly" value="">

在PHP中:

 <input type="text" id="someid" name="somename" <?php if($value) { 
 echo 'readonly="readonly"'; } ?> value="<?php echo $value ?>">

用Javascript:

<script>
 function disableInputField() {
  if (document.getElementById("someid").value) {
    document.getElementById("someid").readOnly = true;
  }
  else {
    document.getElementById("someid").readOnly = false;
  }
 }
</script>

全部一起:

<input type="text" id="someid" name="somename" <?php if($value) { 
 echo 'readonly="readonly"'; } ?> value="<?php echo $value ?>" onblur="Javascript:disableInputField();">

您可以只添加html中要求的readonly,例如。

暫無
暫無

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

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