Q:

jQuery: Toggle between two radio buttons on keydown

I need to toggle the checked value between two radio buttons when the user presses a specific key (in this case its 'd'), but can only get it working in one direction.
HTML:
          <label>
            <input type="radio" id='dark-mode-on' name="dark-mode" />
            <span>On</span>
          </label>
          <label>
            <input type="radio" id='dark-mode-off' name="dark-mode" checked />
            <span>Off</span>
          </label>

JS: (this is being called on keydown)
function toggleDarkModeRadio() {
  if ($('#dark-mode-on').prop('checked', true)) {
    $('#dark-mode-off').prop('checked', true);
  };
  if ($('#dark-mode-off').prop('checked', true)) {
    $('#dark-mode-on').prop('checked', true);
  };
}

But this only toggles the radio once from 'off' to 'on', and won't go back to 'off' again. 
Ive tried a lot of variations and I can't get anything working better than this.
Thanks

A:

Your issue here is that the code in your function doesn't have breaks in it, so when it enters, if it's off, it skips the first if, then goes into the second one. However, if it enters that function and it's on currently, it will go into the first if, set it to off, then by the time it makes it to the second if, it's now off, so it goes in an turns it on again. You can adjust your function to use an else if, or a return like this:
function toggleDarkModeRadio() {
  if ($('#dark-mode-on').prop('checked')) {
    $('#dark-mode-off').prop('checked', true);
    return;
  };
  if ($('#dark-mode-off').prop('checked')) {
    $('#dark-mode-on').prop('checked', true);
    return;
  };
}

or this:
function toggleDarkModeRadio() {
  if ($('#dark-mode-on').prop('checked')) {
    $('#dark-mode-off').prop('checked', true);
  }
  else if ($('#dark-mode-off').prop('checked')) {
    $('#dark-mode-on').prop('checked', true);
  };
}

The other issue is the use of setting the properties in the tested part of the if statement, this causes those properties to be set every time rather than check if they're set.

