Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript/ JQuery Deselecting radio buttons

I have the following javascript, which I want to use to enable the user to deselect a selected radio button by clicking it. (I know this is not standard, but it is required by the system :)

DeselectRadioButton = {
    setup: function () {
        $(".deselectRadioButton").click(function () {
            if ($(this).is(':checked')) {
                alert("I am checked!");
                ($(this).removeAttr('checked'));
            }
        });
    }
};

My issue is that when I select an unselected radio button, it immediately deselects it after the alert shows.

I guess I am receiving the event after the item has changed - how can I fix this code to make my radio button deselectable?

Thanks!

like image 432
laura Avatar asked Dec 13 '22 15:12

laura


2 Answers

However, the main issue is that when I select an unselected radio button, it immediately deselects it after the alert shows.

It seems you can't prevent the default behavior of a radio button with either return false or e.preventDefault() as the radio button always is checked when the click handler is fired. One way around this was to add a separate class to the radio button and use that as your indicator.

$(".deselectRadioButton").click( function(e){
    if($(this).hasClass("on")){
       $(this).removeAttr('checked');
    }
    $(this).toggleClass("on");
}).filter(":checked").addClass("on");

Code example on jsfiddle.

like image 51
Mark Coleman Avatar answered Jan 03 '23 07:01

Mark Coleman


One of the challenges I found while doing this was with groups of radio buttons. The solutions provided work splendidly for a single radio button, but in groups I ran into an issue where de-selecting one and then trying to select another failed (until a second click).

I just came across a solution here that's working splendidly:

var allRadios = $('input[type=radio]')
var radioChecked;

var setCurrent = function(e) {
  var obj = e.target;
  radioChecked = $(obj).attr('checked');
}

var setCheck = function(e) {
  if (e.type == 'keypress' && e.charCode != 32) {
    return false;
  }
  var obj = e.target;
  if (radioChecked) {
    $(obj).attr('checked', false);
  } else {
    $(obj).attr('checked', true);
  }
}    

$.each(allRadios, function(i, val){        
  var label = $('label[for=' + $(this).attr("id") + ']');

  $(this).bind('mousedown keydown', function(e){
    setCurrent(e);
  });

  label.bind('mousedown keydown', function(e){
    e.target = $('#' + $(this).attr("for"));
    setCurrent(e);
  });

  $(this).bind('click', function(e){
    setCheck(e);    
  });
});
like image 27
David Avatar answered Jan 03 '23 07:01

David