jQuery :checkbox 選擇器



jQuery 中的“:checkbox” 選擇器用於選擇所有型別為“checkbox”的 input 元素。

複選框是表單輸入元素,為使用者提供多個選項供選擇。這些複選框可以選中或未選中。

語法

以下是 jQuery 中 :checkbox 選擇器的語法:

$(":checkbox")

引數

以下是上述語法的描述

  • “:checkbox” - 此選擇器將選擇文件中的所有複選框按鈕元素。

示例 1

在下面的示例中,我們使用“:checkbox”選擇器來選擇所有型別為“checkbox”的<input>元素:

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $('button').click(function() {
                $(':checkbox').wrap("<span style='background-color:yellow'>");
            });
        });
    </script>
</head>
<body>
    <form>
        <input type="text" name="username" placeholder="Enter text here"><br>
        Cricket: <input type="checkbox"><br>
        Badminton: <input type="checkbox"><br>
        Football: <input type="checkbox"><br>
        <button>Click</button>
    </form>
</body>
</html>

執行並點選按鈕後,它將選擇所有 type=checkbox 的 input 元素,並用黃色背景色的 span 元素將其包裹。

示例 2

在這個示例中,我們停用表單中的所有複選框按鈕:

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $("button").click(function() {
                $(":checkbox").prop("disabled", true);
            });
        });
    </script>
</head>
<body>
    <form>
        <label>
            <input type="checkbox" name="option" value="1"> Cricket
        </label>
        <label>
            <input type="checkbox" name="option" value="2"> Badminton
        </label>
        <label>
            <input type="checkbox" name="option" value="3"> Cricket
        </label>
        <br>
        <button>Disable All Checkboxes</button>
    </form>
</body>
</html>

點選“停用所有複選框”後,它將選擇所有 type=checkbox 的 input 元素並將其停用。

jquery_ref_selectors.htm
廣告