How can I get dynamic checkbox checked value in jQuery?

Dung Do Tien Nov 05 2020 384

I have a form with a list of categories for user choose but It generates dynamic from an array, and how can I get checked value from the user?

This is my code by Asp.net core:

<div class="custom-select">
    <span>Category</span>
    @foreach (var cate in Model.ListCategory)
    {
        <input id="optCateitem-@cate.Id" type="checkbox" value="@cate.Id" /> 
        <lable for="optCateitem-@cate.Id">@cate.Title</lable>
    }
</div>
<div clas="form-item">
  <button type="button" id="btnSubmit">Submit</button>
</div>

Now I want to click to Submit button, I will alert all options categories selected from the user.

Thanks for any suggestions!!

Have 1 answer(s) found.
  • M

    Marry Christ Nov 08 2020

    I think dynamic or fix, they are the same and we have some way to get checkbox checked value.

    First, you have to set a name for the check box, because we'll get the value selected through the name attribute.

     <input id="optCateitem-@cate.Id" type="checkbox" value="@cate.Id" name="cbCategory" />  

    And in jquery code:

    var checkboxChecked = $('.custom-select input[name=cbCategory]:checked');
    
    checkboxChecked.each(function(){
        // Do stuff here with this
    });  

    You can see some other solution and example from this q&a.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close