LoginSignup
25
22

More than 5 years have passed since last update.

jQueryでshow/hide, addClass/removeClass, disabledの切り替えを一行で書く

Posted at

例えば、表示するとかいうチェックボックスがあったとして

    $("#checkbox").on("click", function() {
        if ($(this).prop("checked")) {
            $('#div').show();
            $('#div').addClass("show");
            $('#div input').prop("disabled", false);
        } else {
            $('#div').hide();
            $('#div').removeClass("show");
            $('#div input').prop("disabled", true);
        }
    }

チェックするとこんな動きをするとしよう

  • DIVを表示
  • DIVに特定のクラスをつける
  • DIV内のinput要素のdisabledを解除する

チェックを外した場合は、上記の逆の処理
こんな処理たちをひたすら一行で書く

show / hide

    if ($(this).prop("checked")) {
        $('#div').show();
    } else {
        $('#div').hide();
    }
    $('#div').toggle($(this).prop("checked"));

addClass / removeClass

    if ($(this).prop("checked")) {
        $('#div').addClass("show");
    } else {
        $('#div').removeClass("show");
    }
    $('#div').toggleClass("show", $(this).prop("checked"));

add or removeするクラスが二つの場合(おまけ)

disabled

    if ($(this).prop("checked")) {
        $('#div input').prop("disabled", false);
    } else {
        $('#div input').prop("disabled", true);
    }
    $('#div input').prop("disabled", !$(this).prop("checked"));

!を忘れずに

まとめて

    $("#checkbox").on("click", function() {
        $('#div').toggle($(this).prop("checked"));
        $('#div').toggleClass("show", $(this).prop("checked"));
        $('#div input').prop("disabled", !$(this).prop("checked"));
    });
    $("#checkbox").on("click", function() {
        var checked = $(this).prop("checked");
        $('#div').toggle(checked).toggleClass("show", checked)
                 .find("input").prop("disabled", !checked);
    });
25
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
22