开发者

jQuery incrementally count selected checkbox and deselected checkbox

I have an ASP.NET web form that has 6 checkbox. 1 checkbox is to call a Function to select all checkbox and show the message "You have selected" 6 "items" (in this case, 6 checkbox). If a user doesn't select the Select All checkbox, they can select or deselect other checkbox individually and the message will be "You have selected" # "items" I'm trying to do this in jQuery, but it's not working yet. Here's the script:

    <script  type="text/javascript">
    //This function works on the click event of SelectAll checkbox
    function selectAll(involker) {
        $('input:checkbox').attr('checked', $(involke开发者_运维百科r).attr('checked'));

        var count = $(":checkbox:checked").length;
        $("#selectedCheckboxMessage").html(count).css({ 'background-color': '#228B22', 'font-weight': 'bolder', 'color': '#FFFFFF', 'padding-left': '0.5em', 'padding-right': '0.5em' });

    }

    //Not working, the message wont's show up on the click event of the checkbox
    $(function() {

        $("input[id ^= ctl00_ContentPlaceHolder1_dlTimeSheet_ctl]").click(showCheckboxStatus);

    });

    function showCheckboxStatus(evt) {

        var numSelected = $(":checkbox:checked").length;
        $("#selectedCheckboxMessage").html("You have selected " + numSelected).css({ 'background-color': '#228B22', 'font-weight': 'bolder', 'color': '#FFFFFF', 'padding-left': '0.5em', 'padding-right': '0.5em' });

    }

The message shows only when a SelectAll checkbox is selected. The message doesn't show if other checkbox is selected or deselected.

I look for an checkbox Id $("input[id ^= ctl00_ContentPlaceHolder1_dlTimeSheet_ctl]") instead of looking for a CSS class. On the markup

<asp:CheckBox ID="cbMarkAsComplete" runat="server" CssClass ="CheckBoxClass"   />

will make the following HTML output:

<span class="CheckBoxClass"><input type="checkbox" name="ctl00$ContentPlaceHolder1$dlTimeSheet$ctl00$cbMarkAsComplete" id="ctl00_ContentPlaceHolder1_dlTimeSheet_ctl00_cbMarkAsComplete"></span>

The CSS class CheckBoxClass is not with the HTML input, that's why I'm looking for checkbox Id instead of checkbox class.

Thank you for the input.


To return just the number of selected checkboxes on the page try changing your selector around a bit and using something like this

$("input[type='checkbox']:checked").length 

That should give you the number of checked checkboxes.

$("input:checked").length 

Will also work but Im a dork for specificity.


You might be better off using a selector like $('.CheckBoxClass input:checkbox')

As for your problem of the number not updating, I'm looking at this line:

var numSelected = $("input.myCheckbox:checked").length;

I don't see the .myCheckbox class anywhere. Try this:

var numSelected = $('.CheckBoxClass input:checked').length;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜