0

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]);
         }
    ...............
   }
5
  • Seems like there will be multiple checkboxes. So put your HTML in a container ( a div or something like that ) then loop through all the checkboxes inside that div. Commented Sep 19, 2013 at 11:42
  • yes multiple check boxes. Its already inside a <td> Commented Sep 19, 2013 at 11:49
  • So inside that javascript function, loop through each checkbox and assign the attribute. Commented Sep 19, 2013 at 11:53
  • I hope i did the same Commented Sep 19, 2013 at 12:05
  • No.. you are looping through the data , not through the checkboxes. Commented Sep 19, 2013 at 12:54

3 Answers 3

2
        **$("#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.

Sign up to request clarification or add additional context in comments.

Comments

0

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]);
   }

Comments

0

This is worked for me-

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.