Alexander Kim
Alexander Kim

Reputation: 18382

How to use $(this) in if/else statement

HTML:

<div class="form-checkboxes" id="edit-field-vozrast-value"><div class="form-item form-type-checkbox form-item-field-vozrast-value-1">
    <input type="checkbox" class="form-checkbox" value="1" name="field_vozrast_value[1]" id="edit-field-vozrast-value-1">  
    <label for="edit-field-vozrast-value-1" class="option">0-3 </label>
</div>

<div class="form-item form-type-checkbox form-item-field-vozrast-value-2">
    <input type="checkbox" class="form-checkbox" value="2" name="field_vozrast_value[2]" id="edit-field-vozrast-value-2">  
    <label for="edit-field-vozrast-value-2" class="option">3-7 </label>
</div>

<div class="form-item form-type-checkbox form-item-field-vozrast-value-3">
    <input type="checkbox" class="form-checkbox" value="3" name="field_vozrast_value[3]" id="edit-field-vozrast-value-3">  
    <label for="edit-field-vozrast-value-3" class="option">7+ </label>
</div>
</div>

JS:

var $age = $('#edit-field-vozrast-value .form-type-checkbox label');
var $vinput = $('#edit-field-vozrast-value .form-type-checkbox input');

    $age.on('click', function() {
        if ($(this).parent().find('input').is(':checked') != true) {
    $(this).addClass('highlight');
    } else {
        $(this).removeClass('highlight'); 
    }
    });

    if ($vinput.is(':checked')) {
      $age.addClass('highlight'); // this adds class highlight to all checkboxes
    }

Logic for this code is following - when a checkbox has a checked value - add class highglight to it's label. But the problem there is when a checkbox has a checked value it adds 'highlight' class to all of the checkboxes, even if they don't have checked value. So how can i use something like $(this) in this case?

UPDATED info. When i click on a checkbox - my page reloads and "highlight" class dissapears, that's why i need to use latest if/else statement to apply this class again to a checkboxes with "checked" statement.

Upvotes: 1

Views: 74

Answers (1)

Alexander Kim
Alexander Kim

Reputation: 18382

#edit-field-vozrast-value .form-type-checkbox input[type=checkbox]:checked + label {
    /* my styles here */
}

That's did a trick, thanks everyone!

Upvotes: 1

Related Questions