Search code examples
jquerycheckboxfor

JQuery: Changing style of element when Checkbox is click


I have a html elements (Using MVC3 Razor)

       <h2 class="price">
              @Html.LabelFor(vm => vm.Price)
              @Html.Encode(@Model.Price)
       </h2>
        <div id="checkbox-price">
              @Html.CheckBoxFor(vm => vm.IncludeToPayment) Include in payment.
        </div>

How can I change the style of the h2 element, (in this case I want to text-decoration: line-through the items inside) when the user uncheck/check the Checkbox using JQUery?

Thanks in advance.


Solution

  • $('#checkbox-price input:checkbox').change(function(){
      if (!$(this).is(':checked')) {
         $('.price').css('text-decoration', 'line-through')
      } else {
         $('.price').css('text-decoration', 'none')
      }
    })
    

    or

      $('#checkbox-price input:checkbox').change(function() { 
                // or $(`input[type="checkbox"]')
                var $obj = $('.price');
                if (!$(this).is(':checked')) {
                  $obj.css('text-decoration', 'line-through'); //or addClass                
                } else {
                  $obj.css('text-decoration', 'none'); // or addClass                
                }
            })