enable/disable input fields with checkboxes (javascript)

…衆ロ難τιáo~ 提交于 2019-12-25 02:47:39

问题


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!


回答1:


You check the state of the checkbox

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



回答2:


Thanks! Also got another solution:

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

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


来源:https://stackoverflow.com/questions/20907150/enable-disable-input-fields-with-checkboxes-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!