Saroj
Saroj

Reputation: 526

Enable button on checkbox selection in MVC 4

Lot of research and tries but didn't work.My Problem is I want to enable my button on check of at least one checkbox from the available list.

Following is the screen: enter image description here

enter image description here

Initially this button is enabled but my requirement is it should be disabled initially and if at least one of the checkbox is checked then it should be enabled.

Here,I have one view as Create inside which one more partial view is there which displays all the list view with the help of one controller method i.e within my Create view one more view is being rendered which displays all the available list.

If it would have been in one view then I would have easily done this as lot of fiddles are there with jquery by getting the id of the checkbox and passing to one jquery function. I know that I need to check the count for the checkbox in order to make my button enable/disable but again we dont have any change event as that in ASP.

Also on click of add , method for controller is begin triggered as:

[HttpPost]
public ActionResult Create(int id, List<MyModel> myModelList)
{
    // code...
}

Here once I click on Add button this controller method is triggered where in my parameters(myModelList) I am able to check which checkbox is checked.So, this thing I need to implement on checking any of the checkbox such that the add button will be enabled on click of which I will be able to add my teams.

So how to implement this or what I need to do for this? Thanks in advance.

Upvotes: 2

Views: 4020

Answers (2)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

you can do it this way:

$(document).on('click', '.checkbox_class', function(){
    if(".checkbox_class:checked").length > 0)
        $('#add_button_id').prop('disabled', false);
    else
        $('#add_button_id').prop('disabled', true);
  }).change();

you can also trigger change on page load:

$(function(){

  $(".checkbox_class").tirgger('change');

})

Upvotes: 3

Abhilash
Abhilash

Reputation: 1610

UPDATE: Oops. Added the :checked pseudo class

This is how you might do it in jQuery

$('#add_button_id').prop('disabled', true); // To disable initially

$(document).on('click', '.checkbox_class', function(){
  if( $('.checkbox_class:checked').length > 0 ){
    $('#add_button_id').prop('disabled', false);
  }
  else{
    $('#add_button_id').prop('disabled', true);
  }
});

You'll have to add the id for the button and classes for checkbox as you have in your html code

Upvotes: 3

Related Questions