Sandy
Sandy

Reputation: 2449

How to get the values of Check Box(@Html.CheckBox) through JQuery JSON data

I want to bind values(checked or not) to a @Html.CheckBox in MVC 3 through JQuery.

This is my HTML-

@using (Html.BeginForm())
{
IEnumerable<SelectListItem> Brands = ViewBag.GetBrands;
foreach (var item in Brands)
{
 @Html.CheckBox("Brands", false, new{value = item.Value});
 <label>@item.Text</label><br />
}}

This is what I tried-

function test {

    var url = "/OfficeManagement/Offices/GetOfficeConfiguration";
    var stringToReverse = rowData.ID;
    var noCache = Date();
    $.get(url, { officeID: stringToReverse, "noCache": noCache }, function (data) {
    for(int i=0;i<data.Configuration.OfficeBrands.count;i++)
         {
          $('#Brands').attr('checked', data.Configuration.OfficeBrands[i]);
         }
    ...............
   }

Upvotes: 0

Views: 1354

Answers (3)

Sandy
Sandy

Reputation: 2449

This is worked for me-

$.each(data.Configuration.OfficeBrands, function(i, brand) {
$(':checkbox[Value="' + brand.ID + '"]').prop('checked', true);});

Upvotes: 0

Ajinder Singh
Ajinder Singh

Reputation: 530

        **$("#Brands").attr("checked"," ")**

In the above line, you are accessing the checkbox using ID, but if there are multiple checkboxes having the same ID, then it will work only for the first checkbox. So, add a class attribute to all the checkboxes and then access them using the class.

Upvotes: 2

Jatin patil
Jatin patil

Reputation: 4288

To make it work you can try as follows,

Create checkbox with the unique name as follows:

int counter = 0;
foreach (var item in Brands)
{
     @Html.CheckBox("Brands" + counter, false, new{value = item.Value});
     counter++;
 }

It will create html markup somewhat similar like this:

<input type="checkbox" name = "Brands0" />
<input type="checkbox" name = "Brands1" />
<input type="checkbox" name = "Brands2" />

Then in jquery you can retrive the values like this:

   for(int i=0;i<data.Configuration.OfficeBrands.count;i++)
   {
      $( "input[name*='"Brands"+i+"]"').attr('checked', data.Configuration.OfficeBrands[i]);
   }

Upvotes: 0

Related Questions