0

I want to be able to enable the checkbox 'present' to disable the input 'dateend'. Here's what I've tried to do, where am I going wrong?

        <input type="month" name="dateend" class="form-control" required>
        <input type="checkbox" id="present" onchange="present()">
        <script>
            function present() {
                document.getElementsByName("dateend").disabled = true;
            }
        </script>
giddz
  • 1
  • 1
    `document.getElementsByName("dateend")` is a NodeList collection...not a single element – charlietfl Jun 07 '20 at 16:32
  • Explanation given by @charlietfl. Solution: replace document.getElementsByName("dateend").disabled = true; with document.querySelector("input[name='dateend']").disabled = true and it should work – Will Jun 07 '20 at 16:38
  • @charlietfl thanks. I've switched the dateend to have 'id="dateend"' rather than a name and tried using 'document.getElementById()' in my javascript with no change in result - any ideas? – giddz Jun 07 '20 at 16:38
  • @Will Thanks Will I've tried this but no luck. I've tried various different ways of doing this without success – giddz Jun 07 '20 at 16:41
  • Might need to remove `required` also since required and disabled have conflicting purposes – charlietfl Jun 07 '20 at 16:42
  • Seems to be working here: https://jsfiddle.net/9skwhc0r/ What do you get? – Will Jun 07 '20 at 16:49
  • @Will I'm getting this output from the console: 'Uncaught TypeError: present is not a function at HTMLInputElement.onchange (employment:109) onchange @ employment:109' – giddz Jun 07 '20 at 16:56
  • You're getting that in jsfiddle? – Will Jun 07 '20 at 17:02
  • @Will No from the JavaScript console on my own page - jsfiddle works fine for me too. I'm quite new to JavaScript, and I'm not sure if I need to be including additional source files for this to work. – giddz Jun 07 '20 at 17:26
  • It's just simple basic JS, no library needed. Looks like your function has not been set. Check for typos and make sure your script is present on your page. – Will Jun 07 '20 at 17:30
  • @Will Simple resolve - the checkbox id is 'present' as is my functions name. When I changed my function name, it worked. In future I'll make sure to keep a distinction between id's and function names. Thanks for your help! – giddz Jun 07 '20 at 17:47
  • Glad you figured it out. You're welcome. – Will Jun 07 '20 at 18:10

0 Answers0