Search code examples
javascriptc#asp.net-mvc

Get the text from Selected Checkbox in MVC checkboxFor with JavaScript


I want to see what the selected value is from the Checkbox that I select. I tried all the javascript and jquery combos out there but all its showing me is "true".

html code for mvc:

    @for (int i = 0; i < Model.TypeOfWorkClassificationCheckBoxes.Count; i++)
 {
 
 <td>
     @Html.CheckBoxFor(x => x.TypeOfWorkClassificationCheckBoxes[i].isSelected, new { @class = "classTest", @id = "chk2" })
     <label>@Model.TypeOfWorkClassificationCheckBoxes[i].towname</label>
     @Html.HiddenFor(x => x.TypeOfWorkClassificationCheckBoxes[i].towid)
     @Html.HiddenFor(x => x.TypeOfWorkClassificationCheckBoxes[i].towname)
 </td>

}

javascript to see what value has been selected

$(document).ready(function () {
$('.classTest').change(function (event) {
    if ($(this).is(':checked')) {
        var theId = $(this).attr('id'); // The id of the checkbox
        var theValue = $(this).val(); // The value field of the checkbox
        console.log(theId);
        console.log(theValue);
    }
});

});

the theId returns "chk2" and the theValue returns "true" but if the checkbox I selected says "text1", I want it to return "text1".

Also tried this: document.getElementById("chk2"); $('#chk2:checked').val();

and it also returns "true"

I really do not want to hardcode all the checkboxes


Solution

  • If you examine the generated html, the checkbox itself doesn't store the text value. You'll need to get it from the hidden field or label instead. e.g.

    $(this).parent().find('label').text();
    $(this).parent().find('#townname').val();