1

I am trying to make a checkbox or checkboxlist from a list. i tried:

@foreach (var bundle in Model.BundleList)
{

    <div>
        <input type="checkbox" name="labels" value="@bundle.BundleType" id="@bundle.BundleType" />
        <label for="@bundle.BundleType">@bundle.BundleType</label>
    </div>
} 

but how can i know which checkbox is selected? i also want to have radiobutton behaviour, which mean only one checkbox can be selected.

Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55
Kimos
  • 99
  • 2
  • 9

1 Answers1

1

Using JQuery you can get selected checkbox by $('input:checkbox:checked') selector.

And you can have radiobutton behaviour of checkbox like following.

$("input:checkbox").click(function () {
    if (!$(this).is(':checked')) {
        $(this).prop('checked', true);
        return;
    }
    $("input:checkbox").not(this).removeAttr("checked");
});

Update: To set selected checkbox value in a hidden field.

Html

<input id="SelectedProducts" name="SelectedProducts" type="hidden" />

Jquery

$("input:checkbox").click(function () {
    if (!$(this).is(':checked')) {
        $(this).prop('checked', true);
        return;
    }

    var checkvalue = $(this).val();
    $('#SelectedProducts').val(checkvalue);

    $("input:checkbox").not(this).removeAttr("checked");
});
Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55
  • i cant get the selected checkbox value and put it in a hidden property i tried: var checkvalue = $('input[name=labels]:checked').map(function () { return this.value; }).get(); i dont know if the checkvalue is correct. how can i assign checkvalue to a propperty in the model? – Kimos Nov 26 '15 at 12:08
  • What do mean by hidden property? Did you mean hidden input? – Ibrahim Khan Nov 26 '15 at 12:23
  • yes hidden input @this.Hidden(m => m.SelectedProducts) – Kimos Nov 26 '15 at 12:51
  • after checking one of the checkbox and see in F12 (developertool) then SelectedProducts value is empty – Kimos Nov 26 '15 at 13:56