user3136387
user3136387

Reputation: 7

How to get selected values for dynamic checkbox in mvc?

I have created a checkbox list in mvc and now i need to take the checked checkbox values using jquery for further coding.But i'm having problem in taking the checkbox values and my code is below

 @{
int i = 1;
foreach (CheckBoxList item in Model.Items)
{
     <input type="checkbox" name="#= Text #" id="#= Text#(i) #" value="#= item.Value #" />
     <span> @item.Text</span>
  <br/>
   i++;
}
}

tell me how to retrieve checkbox values using jquery

Thanks in advance

Upvotes: 0

Views: 6233

Answers (3)

Nitin Varpe
Nitin Varpe

Reputation: 10694

Dont know why you are using normal html tag when u have html helpers provided by razor

cant u use

  @Html.CheckBoxFor(model=>model.chkVal)

Try this

 var checkedValues = $('input[type=checkbox]:checked').map(function()
                {
                    return $(this).val();
                }).get();

checkedValues will contain all values for checked chekboxes

Upvotes: 0

Lucky
Lucky

Reputation: 17345

Try this jquery function,

$(function(){
  $('#save_value').click(function(){
    var val = [];
    $(':checkbox:checked').each(function(i){
      val[i] = $(this).val();
    });
  });
});

or may be try this,

<script type="text/javascript">
$(document).ready(function () {
  var selectedValues="";
  $checkedCheckboxes = $("input:checkbox:checked");
    $checkedCheckboxes.each(function () {
      selectedValues +=  $(this).val() +",";
    });
 alert(selectedValues);//u get a comma separated list
});
</script>

Upvotes: 0

Murali Murugesan
Murali Murugesan

Reputation: 22619

Simply create an array of object and push the values

var allCheckboxInfo=[];

$('input[type="checkbox"]').each(function(){

var checkBoxItemInfo=new {};
checkBoxItemInfo.id=this.id;
checkBoxItemInfo.value=this.value;

allCheckboxInfo.push(checkBoxItemInfo);


});

Then loop through array and do what ever you want to perform

Upvotes: 1

Related Questions