pillarOfLight
pillarOfLight

Reputation: 8982

unchecking radio button is buggy

check out this fiddle: http://jsfiddle.net/5rmEe/

the goal is to uncheck the radio button when the user clicks it if it is checked and check it if it's not checked

but then it appears that the click event triggers twice, making the checking/unchecking highly buggy....

I tried a combination of the

e.stopPropagation();
e.preventDefault();

commands but each of them result in different bugs...

how would I accomplish this goal and fix that code accordingly?

Upvotes: 0

Views: 266

Answers (3)

Miguel-F
Miguel-F

Reputation: 13548

Why not just style the checkboxes to look like radio buttons. That way you get the best of both. You are using checkboxes as they were intended and your boss still won't have a clue ;)

http://ryanfait.com/resources/custom-checkboxes-and-radio-buttons/

There are lot's of examples out there if you start searching for this concept. You will want to do the opposite here but the example is the same.

Can you style an html radio button to look like a checkbox?

Upvotes: 1

MKS
MKS

Reputation: 352

I agree with everyone else that a check box would be better.

However, that being said, here is something that may work for you. First off, the checked attribute being on the radio button marks it checked. So, to remove the check, you have to remove the attribute. However, when clicking on the radio button, it wants to put the attribute back.

My solution is really more of a hack. I am adding another attribute and using that as a flag to determine whether to remove or add the checked attribute. HTH

$('input[type=radio]').each(function(){
  var input = $(this);
  input.click(function(e){
      if(input.attr('cval')==='1'){
          input.attr('cval', '0');
          input.removeAttr('checked');
      }
      else{
          input.attr('cval', '1');
          input.attr('checked', 'checked');
      }
  });
});​

Upvotes: 3

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114377

You need a checkbox - that's what they're for. Messing around with a user's expectation of how standard controls behave is a bad idea.

Upvotes: 0

Related Questions