<script type="text/javascript">
$(document).ready(function () {
$('#change').click(function () {
if ($('#change:checked').length > 0) {
var myType = "checkbox";
} else {
var myType = "radio";
}
var checkbox = $("#Radio1");
checkbox.replaceWith('<input type="' + myType + '" name="option1"/>');
});
</script>
html
<input type="checkbox" name="change" id="change"/>
<label for="changem">Change Buttons</label>
<br/>
<br/>
<input id="Radio1" type="radio" name="option1" value="answer1"/>
When I click a checkbox radio button is converting to checkbox but unclicking is not converting it into radio.
There are a couple of issues with your code:
You forgot to assign an id for the button when you replaced its contents so the next time your
$('#Radio1')selector returns nothingYou declared the
myTypevariable inside theifwhich is local to this scope.You didn’t properly close the
})between thedocument.readyhandler and theclickhandler.Here’s what I would recommend you:
And here’s a live demo.