jQuery: disabling prop IF checked

224 views Asked by At

I have some script that I have written and it works exactly how I would like it too, but it seems pretty lengthy for what it does: http://jsfiddle.net/x6xbymmL/

$(".class2").prop("disabled", true);
$(".class3").prop("disabled", true);

$('input[class^="class"]').click(function() {
var $this = $(this);

if ($this.is(".class1")) {
    if ($(".class1:checked").length > 0) {
        $(".class1").prop("disabled", true);
        $(".class2").prop("disabled", false);
        $(".class3").prop("disabled", false);
    } else {
        $(".class1").prop("disabled", false);
        $(".class2").prop("disabled", true);
        $(".class3").prop("disabled", true);
    }
}

if ($this.is(".class2")) {
    if ($(".class2:checked").length > 0) {
        $(".class1").prop("disabled", true);
        $(".class2").prop("disabled", false);
        $(".class3").prop("disabled", true);
    } else {
        $(".class1").prop("disabled", true);
        $(".class2").prop("disabled", false);
        $(".class3").prop("disabled", false);
    }
}

if ($this.is(".class2")) {
    if ($(".class2:checked").length > 1) {
        $(".class1").prop("disabled", true);
        $(".class2").prop("disabled", true);
        $(".class3").prop("disabled", true);
    } else {
        $(".class1").prop("disabled", true);
        $(".class2").prop("disabled", false);
        $(".class3").prop("disabled", true);
    }
}

if ($this.is(".class3")) {
    if ($(".class3:checked").length > 0) {
        $(".class1").prop("disabled", true);
        $(".class2").prop("disabled", true);
        $(".class3").prop("disabled", true);
    } else {
        $(".class1").prop("disabled", true);
        $(".class2").prop("disabled", false);
        $(".class3").prop("disabled", true);
    }
}

});

I am trying to figure out if I have written it the best I can or if there is a better way? Also a nicety would be to disable all others in group except the checked one so that the user can go back if they have checked the wrong option... I really struggled getting this to work :/

1

There are 1 answers

6
Howard Renollet On BEST ANSWER

Here is a significantly shorter version of your code that has the exact same functionality. See it work here: http://jsfiddle.net/x6xbymmL/1/

$(".class2, .class3").prop("disabled", true);
$('input[class^="class"]').click(function () {
    if ($(".class1:checked").length > 0) {
        $(".class1").prop("disabled", true);
        $(".class2, .class3").prop("disabled", false);
    }
    if ($(".class2:checked").length > 0 || $(".class3:checked").length === 1) {
        $(".class3").prop("disabled", true);
    }
    if ($(".class3:checked").length === 1 || $(".class2:checked").length === 2) {
        $(".class3, .class2").prop("disabled", true);
    }
});

You really had way too many if statements in there for what you were trying to accomplish. It was working, and you were being thorough, but most of it was unnecessary.