1

I can't seem to get my button to re-enable after it's been disabled. Currently, if nothing is checked and I mouseover it, the button disables. It stays enabled if I have something checked, but if I first hover over then button, with nothing checked, I can't get it to re-enable if I check something.

Here's My JS:

var inputs = document.getElementsByTagName('input');
var letsCookButton = document.querySelector('#letsCook');

letsCookButton.addEventListener('mouseover', checkIfChecked);

function checkIfChecked() {
  letsCookButton.disabled = true;
  for (var i = 0; i < inputs.length; i++) {
    if (inputs[i].checked) {
      letsCookButton.disabled = false;
    }
  }
}

Here's my HTML:

div class="mainBox" id="box-one">
          <p id="left-box-title">What are you looking for?<span>*</span></p>
          <ul>
            <li><input type="radio" name="food" id="side-food"> Side</li>
            <li><input type="radio" name="food" id="main-food"> Main Dish</li>
            <li><input type="radio" name="food" id="dessert-food"> Dessert</li>
            <li><input type="radio" name="food" id="entire-meal"> Entire Meal</li>
          </ul>
          <button id="letsCook">LET'S COOK!</button>
        </div>
mfaccord
  • 225
  • 1
  • 3
  • 14

1 Answers1

1

You will have to slightly rethink how you want the UX of your app to work, because disabled elements do not produce events.

Since at least one radio button will remain checked after the first click, I would suggest disabling the button from the start and then enabling it on a radio click event.

<div class="mainBox" id="box-one">
  <p id="left-box-title">What are you looking for?<span>*</span></p>
  <ul id="radio-group">
    <li><input type="radio" name="food" id="side-food"> Side</li>
    <li><input type="radio" name="food" id="main-food"> Main Dish</li>
    <li><input type="radio" name="food" id="dessert-food"> Dessert</li>
    <li><input type="radio" name="food" id="entire-meal"> Entire Meal</li>
  </ul>
  <button id="letsCook" disabled>LET'S COOK!</button>
</div>
var inputGroup = document.querySelector('#radio-group');
var letsCookButton = document.querySelector('#letsCook');

inputGroup.addEventListener('click', function () {
    letsCookButton.removeAttribute('disabled')
});

Working example in JS Fiddle: https://jsfiddle.net/Ollie1700/wxn9f63p/4/

Ollie
  • 1,355
  • 1
  • 10
  • 22