Skip to content Skip to sidebar Skip to footer

How Can I Change A Checkbox For A Radio Button Using Jquery?

How can I change a checkbox for a radio button using jQuery?

Solution 1:

var checkbox = $("#myCheckbox");
checkbox.replaceWith('<input type="radio" name="'+checkbox.attr('name')+'" value="'+checkbox.attr('value')+'" />');

Or with jQuery 1.4

var checkbox = $("#myCheckbox");
$("<input>",{
    type:'radio',
    name: checkbox.attr('name'),
    value: checkbox.attr('value')
}).replace(checkbox);

You change change the type attribute because it causes problems in IE.

Solution 2:

given:

<inputtype="checkbox"name="change"id="change"><labelfor="changem">Change Buttons</label><br><br><divid="btngroup"><span><inputtype="radio"name="btngroup"id="btn-1"></span><labelfor="btn-1">Button 1</label><br><span><inputtype="radio"name="btngroup"id="btn-2"></span><labelfor="btn-2">Button 2</label><br><span><inputtype="radio"name="btngroup"id="btn-3"></span><labelfor="btn-3">Button 3</label><br></div>

jQuery:

$(document).ready(function() {
  $('#change').click(function() {
    if( $('#change:checked').length > 0 ) {
      var myType = "checkbox";
    }  else {
      var myType = "radio";
    }
     $("#btngroup span").each(function(i) {
     $(this).html('<input type="' + myType + '" name="btngroup" id="btn-' + (i+1) + '">');
    });
  });
});

DEMO

Solution 3:

i think you can't change the type attribute.

as an alternative, you can use divs: one for the checkboxes and other for the radios. and use the show() / hide() methods...

Post a Comment for "How Can I Change A Checkbox For A Radio Button Using Jquery?"