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.

5
  • Why do you need checkboxes if you are going to uses them like radio buttons? Commented Nov 26, 2015 at 7:57
  • If you want radio button behavior, then use radio buttons (not checkboxes) Commented Nov 26, 2015 at 7:57
  • 1
    stackoverflow.com/questions/4697941/… Commented Nov 26, 2015 at 7:58
  • @Kimos, add a class to all checkboxes and find checked checkboxes by $('.class_name:checked') Commented Nov 26, 2015 at 7:59
  • Hi, i made some changes and i added a jquery script to make the radiobutton behaviour Commented Nov 26, 2015 at 8:13

1 Answer 1

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");
});
Sign up to request clarification or add additional context in comments.

4 Comments

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?
What do mean by hidden property? Did you mean hidden input?
yes hidden input @this.Hidden(m => m.SelectedProducts)
after checking one of the checkbox and see in F12 (developertool) then SelectedProducts value is empty

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.