Skip to content Skip to sidebar Skip to footer

Improving Use Of Radio Buttons To Enable/disable Form Fields

I have two radio buttons, and two corresponding form fields. Depending on which radio button is selected, one form field gets disabled and the other gets enabled. My code works, bu

Solution 1:

You can test the checked state within the onchange handler, and simply invoke the onchange handler (which I believe you should be using instead of onclick) once when the page loads:

$(document).ready(function() {
    $("#element_link_link_type_internal").change(function() {
        $("#element_link_page_id").attr("disabled", !this.checked);
        $("#element_link_url").attr("disabled", this.checked);
    }).change(); // invoke once to set up initial state
});

Solution 2:

This is untested and based on your comments/answer:

jQuery < 1.6:

$(document).ready(function() {

    var$type = $('input[name="element_link[link_type]"]'),
        $pageId = $("#element_link_page_id"),
        $url = $("#element_link_url");

    $type.change(function() {

        if ($type.filter(":checked").val() === "internal") {

            $pageId.removeAttr("disabled");
            $url.attr("disabled", "disabled");

        } else {

            $url.removeAttr("disabled");
            $pageId.attr("disabled", "disabled");            

        }

    }).change();

});

jQuery >= 1.6

$(document).ready(function() {

    var$type = $('input[name="element_link[link_type]"]'),
        $pageId = $("#element_link_page_id"),
        $url = $("#element_link_url");

    $type.change(function() {

        var isDisabled = ($type.filter(":checked").val() === "internal");

        $pageId.prop("disabled", !isDisabled);
        $url.prop("disabled", isDisabled);

    }).change();

});

Solution 3:

@karim79, your answer got me started but it didn't work when the 2nd radio button was selected. It only worked when the 1st radio button was selected.

I came up with this, and it seems to do the trick. I'd welcome anyone to offer additional improvements though. JavaScript blows my mind.

$(document).ready(function() {
$("input[name='element_link[link_type]']").change(function() {
    var v = $("input[name='element_link[link_type]']:checked").val()
    $("#element_link_page_id").attr("disabled", v == 'internal' ? "" : "disabled");
    $("#element_link_url").attr("disabled", v == 'internal' ? "disabled" : "" );
}).change(); // invoke once to set up initial state
});

Post a Comment for "Improving Use Of Radio Buttons To Enable/disable Form Fields"