0

Please note, I have referred to this answer and my solution is currently using that approach.

Here is my HTML:

<head>
<script>

document.getElementById('average_price').onchange = function() {
    document.getElementById('average_price_symbol').disabled = !this.checked;

};

</script>
</head>

<center>
<form action="/custom" method="POST">
    <h2>Generate Custom Report</h2>
        <br>

        <input type="checkbox" id="average_price" name="average_price"> <b>Average Price</b>
        <br>
        <input type="text" id="average_price_symbol" name="average_price_symbol" placeholder="symbol" disabled>
        <br>

        <input type="submit" value="RUN">
</form>

</center>

When the form loads, the text field is disabled, however, the checkbox does not change the state of the field. I'm not exactly sure what's going wrong.

j08691
  • 204,283
  • 31
  • 260
  • 272
Harrison
  • 5,095
  • 7
  • 40
  • 60

3 Answers3

0

Your script executes before your HTML loads, so this doesn't find anything:

document.getElementById('average_price')

Move the script to the bottom of the page, traditionally just inside the </body> tag.

David
  • 208,112
  • 36
  • 198
  • 279
0

Disable your input programatically

Reminder: ALWAYS put your scripts before the closing body tag

HTML

<h2>Generate Custom Report</h2>
  <br>
  <input type="checkbox" id="average_price" name="average_price"> <b>Average Price</b>
  <br>
  <input type="text" id="average_price_symbol" name="average_price_symbol" placeholder="symbol" >
  <br>
  <input type="submit" value="RUN">

JS

var checkbox = document.getElementById('average_price');
var input = document.getElementById('average_price_symbol');

input.disabled = true;
checkbox.addEventListener('change', function (e) {
  console.log('CHECKED', this.checked);
  input.disabled = !this.checked;
  (!input.disabled && input.focus());
});
AngelSalazar
  • 3,080
  • 1
  • 16
  • 22
0

Adding the code to a document ready function will help.

$('document').ready(function(){ document.getElementById('average_price') });
jkort13
  • 11
  • 2