Call javascript function when specific radio become unselected

Viewed 72

I have some radio inputs and I would like to call a JS function only in the case where the id3 radio is selected and becomes unselected.

I searched, but I found only solutions, where only checked/unchecked status is checked:

$("input:radio").change(function() {
  if ($("#id3").is(":checked")) {
    alert('checked');
  } else {
    alert('unchecked');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="shipping_method" value="1" id="id1" data-refresh="5" class="">
<input type="radio" name="shipping_method" value="2" id="id2" data-refresh="5" class="">
<input type="radio" name="shipping_method" value="3" id="id3" data-refresh="5" class="">

2 Answers

What you can do is add a watcher variable to find out whether you are deselecting the radio button.

var isChecked = false;
$("input:radio").change(function () {
  if ($("#id3").is(":checked")) {
        isChecked = true;
    } else {
      if (isChecked) {
        alert("Unchecked");
        isChecked = false;
      }

    }
});

CodePen: https://codepen.io/ashfaq_haq/pen/LYYjLrv?editors=1010

You will need to keep track of when you last clicked it, to see if you need to say that it was unselected.

Plain JS

This is fairly simple to do in pure JavaScript. You can utilize the data-* attribute design to store the state of when an element was last checked.

let targetEl = document.getElementById('id3');

Array.from(document.querySelectorAll('input[type="radio"]')).forEach(radioEl => {
  radioEl.addEventListener('change', function(e) {
    if (e.target.id === targetEl.id && e.target.checked) {
      alert(e.target.id + ' - checked');
      e.target.setAttribute('data-waschecked', true);
    } else if (targetEl.getAttribute('data-waschecked') === 'true') {
      alert(targetEl.id + ' - unchecked');
      targetEl.setAttribute('data-waschecked', false);
    }
  });
});
<input type="radio" name="shipping_method" value="1" id="id1" data-refresh="5">
<input type="radio" name="shipping_method" value="2" id="id2" data-refresh="5">
<input type="radio" name="shipping_method" value="3" id="id3" data-refresh="5">

jQuery

This advanced solution allows you to monitor multiple radio buttons. It is written mostly in jQuery.

const trackableIds = [ 'id1', 'id3' ];

$('input[type="radio"]').on('change', function(e) {
  let $target = $(e.target),
      isTrackable = trackableIds.includes($target.attr('id'));
  if (isTrackable && $target.is(':checked')) {
    alert($target.attr('id') + ' - checked');
    $target.attr('data-waschecked', true);
  }
  trackableIds.filter(trackId => trackId !== $target.attr('id'))
    .forEach(trackId => {
      let $trackable = $('#' + trackId);
      if ($trackable.attr('data-waschecked') === 'true') {
        alert($trackable.attr('id') + ' - unchecked');
        $trackable.attr('data-waschecked', false);
      }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="shipping_method" value="1" id="id1" data-refresh="5">
<input type="radio" name="shipping_method" value="2" id="id2" data-refresh="5">
<input type="radio" name="shipping_method" value="3" id="id3" data-refresh="5">

As a jQuery plugin

Nearly identical behavior to the jQuery above, but as a plugin. There are even custom callback function options for checking/unchecking.

(($) => {
  $.fn.trackRadio = function(ids, opts) {
    this.on('change', function(e) {
      let $target = $(e.target), isTrackable = ids.includes($target.attr('id'));
      if (isTrackable && $target.is(':checked')) {
        opts.onCheckFn($target);
        $target.attr('data-waschecked', true);
      }
      ids.filter(trackId => trackId !== $target.attr('id')).forEach(trackId => {
        let $trackable = $('#' + trackId);
        if ($trackable.attr('data-waschecked') === 'true') {
          opts.onCheckFn($trackable);
          $trackable.attr('data-waschecked', false);
        }
      });
    });
  }
})(jQuery);

$('input[type="radio"]').trackRadio(['id1', 'id3'], {
  onCheckFn : function($radio) {
    alert($radio.attr('id') + ' - checked');
  },
  onUncheckFn : function($radio) {
    alert($radio.attr('id') + ' - unchecked');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="shipping_method" value="1" id="id1" data-refresh="5">
<input type="radio" name="shipping_method" value="2" id="id2" data-refresh="5">
<input type="radio" name="shipping_method" value="3" id="id3" data-refresh="5">

Related