user3157722
user3157722

Reputation: 1

enable/disable input fields with checkboxes (javascript)

I'm trying to make a html5 form with different input fields, with a checkbox that can enable/disable input fields.

When the checkbox is selected, it should be possible to enter data into an input field. When the checkbox isn't selected, it shouldn't be possible to enter data to the input field.

I already tried this (just to try if enabling/disabling works):

<script>
document.getElementById("checkbox").onclick = function() {
    document.getElementById("inputfield").disabled=true;
}
</script>

The input field is disabled when the user clicks on the checkbox, so disabling fields works but I don't know how it works with selecting the checkbox and re-enabling.

This is my first time using javascript so any help is greatly appreciated!

Upvotes: 0

Views: 1847

Answers (2)

user3157722
user3157722

Reputation: 1

Thanks! Also got another solution:

function active()
{
  if(document.getElementById('checkbox').checked)
     document.getElementById('inputfield').disabled=false;

  else
     document.getElementById('inputfield').disabled=true;
}

Upvotes: 0

epascarello
epascarello

Reputation: 207537

You check the state of the checkbox

document.getElementById("inputfield").disabled= this.checked;

Upvotes: 2

Related Questions