Balu Balu - 4 months ago 19
Javascript Question

Unable to get the unchecked checkbox values

I have a FieldItems dictionary in ASP.NET model and this dictionary has values as below.

Age - checkbox, Name - text, Company - text

In my view file I was creating controls based on key, value pair which are available in the dictionary.

<div class="row cloneMe">
<table>
@foreach (var item in Model.FieldItems)
{
<tr>
@if (item.Value == "checkbox")
{
<td>@item.Key</td>
<td> <input class="associationCheckbox" type="@item.Value" name="@item.Key" value="false" placeholder="@item.Key" /></td>
}
else if (item.Value == "number")
{
<td>@item.Key</td>
<td> <input type="number" name="@item.Key" value="0" ng-required="true" placeholder ="@item.Key" /> </td>
}
else
{
<td>@item.Key</td>
<td> <input type="text" name="@item.Key" value="" ng-required="true" placeholder ="@item.Key" /> </td>
}
</tr>
}
</table>
</div>


<span>
<button type="button" id="associationAdd" class="btn btn-success" style="float:none;cursor:pointer" ng-click="RemoveWidget()">AddPerson</button>
</span>
<span>
<button type="button" id="associationRemove" class="btn btn-danger" style="float:none;cursor:pointer" ng-click="AddWidget()">Remove</button>
</span>


Adding to previousone, I can include/remove the chosen fields based on button click as using below code.

$("#associationAdd").on("click", function () {
$(".cloneMe:last").clone(true).insertAfter(".cloneMe:last");
});

$("#associationRemove").on("click", function () {
if ($(".cloneMe").length > 1) {
$(".cloneMe:last").remove();
}
});;


After Adding my controls on ASP.NET page, I was reading control values.

enter image description here

[HttpPost]
public ActionResult Index(FormCollection formCollection)
{
foreach (var key in formCollection.Keys)
{
var value = formCollection[key.ToString()];
}

}


On clicking submit button, I can read Name and age values. However, I can get only checked checkbox values.
If I have three checkboxes and all are unchecked then key of checkbox is not showing in formCollection of Acton Result.

I have tried the following way to set the checkbox state but no result.

$("input:checkbox[class=associationCheckbox]").each(function () {

if ($(this).attr('checked')) {
$(this).val('true');
} else {
$(this).val('false');
}
});

Answer

In order to the checked attribute of checkbox using jquery use:

$(this).prop('checked', true);

If you are using jquery version earlier than 1.6 the use

$(this).attr('checked', 'checked');

To check whether a checkbox is checked or not use:

$(function(){
 $('.associationbox').on('click', function(){
    if($('.associationbox').prop('checked')){
    alert('checked');
  }

 })

})

JSFIDDLE