0

I am using a jQuery that is styling my checkbox, meaning that, on click, it changes the style of the checkbox (onchange actually). My problem is: the values I select are taken from a database, on one part, and modified by users on the other part. So, if a condition is fulfilled, I want that radio button to be checked. I wonder how can I do this in my jQuery function: (code below:)

  <script type="text/javascript">
    $(document).ready(function(){
$(".CheckBoxClass").change(function(){
    if($(this).is(":checked")){
        $(this).next("label").addClass("LabelSelected");
    }else{
        $(this).next("label").removeClass("LabelSelected");
    }                            

});

    });
   </script>

And the HTML:

  <form id="address" method="POST" action="<?= Route::url('Save user preferences' , array('user_id' => $user));?>">
 <? foreach ($prefered_products as $pp): ?>
 <input id="CheckBox[<?= $pp; ?>]" type="checkbox" class="CheckBoxClass" style="display: none;" name="user_preferences_preference[<?= $pp->id ?>]" value="<?= $pp ?>" checked="checked" />
 <label id="Label[<?= $pp; ?>]" for="CheckBox[<?= $pp; ?>]" class="CheckBoxLabelClass"><?= $pp->product; ?></label>


Salveaza preferintele tale

The function is only onchange. I also want that, if exists the attr cheched = "checked", the checkbox to be checked (the checked style to be displayed).

Is this possible in the given conditions?

2 Answers 2

2
$(".CheckBoxClass:checked").each(function(){
  $(this).next('label').addClass("LabelSelected");
});
Sign up to request clarification or add additional context in comments.

Comments

0

You could manually trigger the change effect after your .change() is declared, untested but should work:

$(".CheckBoxClass").trigger('change');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.