How can I change a checkbox for a radio button using jQuery?
Asked
Active
Viewed 1.1k times
4
-
It's certainly possible. What do you need it for, in what kind of a scenario? – Pekka Mar 10 '10 at 20:20
-
I have a radio button and I need that if the value is oone of them, 5 checkbox get transformed in 5 radio buttons and vice-versa, I hope you understand. – Jedi Master Spooky Mar 10 '10 at 20:22
3 Answers
11
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.

PetersenDidIt
- 25,562
- 3
- 67
- 72
-
-
I don't know if that did work at jQuery 1.4, but it doesn't at 1.6. Instead use: `var checkbox = $("#myCheckbox"); checkbox.replaceWith($("",{ type:'radio', name: checkbox.attr('name'), value: checkbox.attr('value') }));` – MarkD Apr 20 '12 at 13:15
4
given:
<input type="checkbox" name="change" id="change">
<label for="changem">Change Buttons</label><br><br>
<div id="btngroup">
<span><input type="radio" name="btngroup" id="btn-1"></span>
<label for="btn-1">Button 1</label><br>
<span><input type="radio" name="btngroup" id="btn-2"></span>
<label for="btn-2">Button 2</label><br>
<span><input type="radio" name="btngroup" id="btn-3"></span>
<label for="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

ghoppe
- 21,452
- 3
- 30
- 21
2
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...

Ju Nogueira
- 8,435
- 2
- 29
- 33