jquery Type Change Security

Demonstrate a security feature of jQuery when changing a checkbox into radio button

by richbuff

HTML

<form>
    <input type="checkbox" name="mycb" />
    <input type="checkbox" name="mycb" />
    <input type="checkbox" name="mycb" />
</form>
<br />
<br />
<button id="cwjq">change with jQuery</button>
<button id="cwjs">change with JavaScript</button>
<button id="cwjq2">change by replacing</button>

JavaScript

$().ready(function () {
            $("#cwjs").click(function () {
                changeWithJavascript();
            });

            $("#cwjq").click(function () {
                changeWithjQuery();
            });

            $("#cwjq2").click(function () {
                return changeByReplacing();
            });
        });


        function changeWithjQuery() {
            try {
                $("input[type='checkbox']").attr("type", "radio");
            } catch (ex) {
                alert(ex);
            }

            return false;
        }

        function changeWithJavascript() {
            $("input[type='checkbox']").each(function (idx, elem) {
                $(this)[0].type = "radio";
            });
            return false;
        }

        function changeByReplacing() {
            $("input[type='checkbox']").each(function () {
                $("<input type='radio' />").attr({
                    name: this.name,
                    value: this.value
                }).insertBefore(this);
            }).remove();

            return false;
        }