Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting a checkbox as selected when loading from code behind

I am loading the checkboxlist's listitems in the code behind as follows;

'load the fuel types into the checklist box
    For Each newitem As String In GetFuelTypes(Request.PhysicalApplicationPath & "OtherDataFiles\dataXML.xml")
        cblFuelstoDisplay.Items.Add(New ListItem(newitem))
    Next

I use the following jquery to change the css style when an item is checked;

$(document).ready(function () {
          $("#cbxarea").on("change", ":checkbox", function () {
              $(this).siblings("label").toggleClass("checkboxselected", $(this).is(":checked"));

          });              
      });

and that works perfectly fine.BUT, I set the first checkboxlist item as selected in the aspx codebehind and you CANNOT set the css style there. How do I change the style on page load in jquery after the doc.ready? I tried adding this to the script but it did not work

$("#cbxarea:checkbox").each(function () {
              if( $(this).is(":checked")) {
                  $(this).toggleClass("checkboxselected");
              }
          });

Here is the checkbox markup

 <fieldset style="height:140px;">
                <legend>Select a Fuel Type to Display</legend> 
                <div id="cbxarea" class="checkbox">
                    <asp:CheckBoxList ID="cblFuelstoDisplay" runat="server"  AutoPostBack="True" >              
                    </asp:CheckBoxList>
                </div>              
            </fieldset>
like image 245
dinotom Avatar asked Jun 04 '26 04:06

dinotom


1 Answers

You should use space between the selectors, also you are not selecting sibling label elements.

$("#cbxarea input[type=checkbox]:checked")
                             .siblings('label')
                             .addClass("checkboxselected");

You can also trigger the change event:

$("#cbxarea").on("change", "input[type=checkbox]", function() {
    $(this).siblings("label").toggleClass("checkboxselected", this.checked);
}).change();

Note that if your checkboxes are static there is no need to use event delegation.

$("#cbxarea input[type=checkbox]").on("change", function() {  }).change();
like image 156
undefined Avatar answered Jun 07 '26 14:06

undefined



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!