设置输入字段只读使用Javascript

问题描述 投票:-3回答:2

我通过另一个脚本动态设置SecretAttribute价值,但目前我在做的姓名输入字段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>
javascript html
2个回答
2
投票

函数调用的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>

0
投票

如果您使用旧版本浏览器尝试使用setAttribute,类似...

  var SecretElement = document.getElementById('SecretAttribute');
  if (SecretElement.checked) {
    document.getElementById('Name').setAttribute("readonly","readonly");
  }
© www.soinside.com 2019 - 2024. All rights reserved.