Manna
Manna

Reputation: 31

Check if the Checkbox is checked or no in MVC

I want to check if the checkbox is checked or no. I have the following code:

<div class="checkbox">
@Html.HiddenFor(model => model.VehicleTypeSelected)
@Html.ValidationMessageFor(model => model.VehicleTypeSelected)    
<br>
@foreach (VehicleType vt in ViewBag.VehicleTypes)
{
    <label><input type="checkbox" value="@vt.VehicleTypeID" name="VehicleTypeIds" class="vehicle-type-selector" /> @vt.Name 
    <br></label>
}

I want to use this approach:

                    $('#checkBoxForm :checkbox').click(function() {
                    var $this = $(this);
                    if ($this.is(':checked')) {
                        // the checkbox was checked 
                    } else {
                        // the checkbox was unchecked
                    }
                });

if the checkbox (isUniversal) is checked, I want to disable all the checkboxes(vehicleTypes)

Upvotes: 0

Views: 1252

Answers (3)

madalinivascu
madalinivascu

Reputation: 32354

use the attr() function

Try (assuming isUniversal is a class ):

$(".isUniversal").on('click',function(){
      if ($("this").attr('checked') == 'checked') {
        $('.vehicle-type-selector').removeAttr('checked').attr('disabled','disabled'); 
      }
    })

or

 $(".isUniversal").on('click',function(){
              if( $('this').is(":checked") ){
                $('.vehicle-type-selector').removeAttr('checked').attr('disabled','disabled');
              }
            })

Upvotes: 0

Christos
Christos

Reputation: 53958

You can check if any vehicle type is checked, using just this:

$(function(){
    var isAnyVehicleTypeChecked = $(".vehicle-type-selector").is(":checked").length > 0
});

Furthermore, using the following

$(function(){
    var checkedVehicleTypes = $(".vehicle-type-selector").is(":checked");        
});

you can pick all the checkboxes that has the class vehicle-type-selector and they are checked.

Upvotes: 1

John
John

Reputation: 4991

if( $('.vehicle-type-selector').is(":checked") ){
  // Do something
}

Upvotes: 0

Related Questions