Varshini
Varshini

Reputation: 199

Can't enable/disable textbox when toggling checkbox

this is my code.jsp file and I've written javascript in it to enable/disable textbox name=uinp when toggling checkbox name=input but it is not working!

<html>
<body>
    <form action="compile.jsp" method="get"> 
        Custom Input: <input type="checkbox" name="input" onchange="toggle('input','uinp')"><br><br>     
        <textarea rows="5" cols="15" name="uinp" style="display: none"></textarea><br><br>
        <br><input type="submit" value="Submit">
        <input type="reset" value="Cancel">
    </form>
    <script>
       function toggle(chk,txt)
       {     
            if(document.getElementById(chk).checked)  
                document.getElementById(txt).style.display='';
            else
               document.getElementById(txt).style.display='none';
       }
    </script>
</body>
</html>

Please anyone help me with this!

Upvotes: 1

Views: 360

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115242

You need to set id for textarea otherwise getElementById() returns null, since there is no element with that id. Also you can pass this context to refer the checkbox.

<form action="compile.jsp" method="get">
  Custom Input:
  <input type="checkbox" name="input" onchange="toggle(this,'uinp')">
  <br>
  <br>
  <textarea rows="5" cols="15" id="uinp" style="display: none"></textarea>
  <br>
  <br>
  <br>
  <input type="submit" value="Submit">
  <input type="reset" value="Cancel">
</form>
<script>
  function toggle(ele, txt) {
    if (ele.checked)
      document.getElementById(txt).style.display = '';
    else
      document.getElementById(txt).style.display = 'none';
  }
</script>

Upvotes: 2

Related Questions