Search code examples
javascripthtmlcheckboxreadonlyservicenow

JS if statement doesn't seem to work


I have a checkbox and if it is checked, I want text boxes to be editable. If it remains unchecked, then I want the text boxes to be readOnly. Here is my JS:

if (document.getElementById('itemize').checked==false) {
    document.getElementById('budget_1').readOnly = true;
} else  {
    document.getElementById('budget_1').readOnly = false;
     }  

My HTML for the checkbox:

<input type="checkbox" id="itemize" style="width: 20px; height: 20px;" />

The JS seems to make the text box readOnly just fine, but when I make sure the checkbox is checked, the text box remains readOnly. Any suggestions?


Solution

  • You would need to use an event handler to run when the checkbox changes state

        var 
           budget_1 = document.getElementById('budget_1'),
           itemize = document.getElementById('itemize');
         
        itemize.addEventListener("change", readonly);
    
        function readonly(){
            if (itemize.checked==false) {
                budget_1.readOnly = true;
            } else {
               budget_1.readOnly = false;
            }  
        }
    <input type="checkbox" id="itemize"/>
    <input type="text" id="budget_1" readonly/>