Skip to content

Instantly share code, notes, and snippets.

@eric1234
Last active November 13, 2018 12:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save eric1234/baf9ccdfa94eaa7a0820 to your computer and use it in GitHub Desktop.
Save eric1234/baf9ccdfa94eaa7a0820 to your computer and use it in GitHub Desktop.
Modified radio buttons so they are allowed to be unchecked

Include this script and all your radio buttons can be unchecked. The result is the radio box group goes back to a state where no radio is checked. Sort of a cross between a radio button and a checkbox. This means your backend should be prepared for that field to be empty even if you populated it when the page was loaded.

This script assumes it is operating in a Turbolinks environment as it initializes using the page:change event. If you are not using Turbolinks you will want to change it to use the jQuery ready event.

Install with gist-dep with:

gist-dep add -p app/assets/javascripts/uncheck-radio.js.coffee baf9ccdfa94eaa7a0820
# https://gist.github.com/eric1234/baf9ccdfa94eaa7a0820
$ = jQuery
$(document).on 'page:change', ->
for radio in $ '[type=radio]'
radio.setAttribute 'data-was-checked', radio.checked
return
$(document).on 'radio:state-update', '[type=radio]', ->
for radio in $ "[type=radio][name='#{@name}']"
radio.setAttribute 'data-was-checked', radio.checked
return
$(document).on 'click', '[type=radio]', ->
@checked = false if @getAttribute('data-was-checked') == 'true'
$(@).trigger 'radio:state-update'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment