-3

I'm setting the value for SecretAttribute dynamically via another script, but at the moment I'm having difficulties making the Name input field as readonly.

Tried setting the getElementByID by SecretAttribute and SecretElement, but no dice..

<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>
Liam
  • 22,818
  • 25
  • 93
  • 157
Rain
  • 249
  • 3
  • 13
  • What does *but no dice* mean? What exactly isn't working? that is the correct way to set the readonly attribute. Have you debugged this code? – Liam Feb 06 '19 at 09:40
  • Why is the input element before the html element? – Quentin Feb 06 '19 at 09:41

2 Answers2

2

Function call was inside the if statement. Put the if condition inside the call

  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>
ellipsis
  • 11,498
  • 2
  • 13
  • 33
0

If your using older browsers try using setAttribute, something like...

  var SecretElement = document.getElementById('SecretAttribute');
  if (SecretElement.checked) {
    document.getElementById('Name').setAttribute("readonly","readonly");
  }
Liam
  • 22,818
  • 25
  • 93
  • 157
Rik Lewis
  • 723
  • 4
  • 10