Raj
Raj

Reputation: 555

Why checkbox is not working using JQuery

I have 3 checkboxes in a view. When anyone of those is checked, I want to add 3 to the value of a javascript variable named cost. If anyone of the checkboxes is then unchecked, I want to subtract 3 from the value of cost.

Currently my code always subtracts 3 when a checkbox is checked or unchecked. How can I add 3 when a checkbox is checked?

HTML

<div class="panel-heading">Checkboxes</div>
<div id="chkbox" class="panel-body">
    <div>
        @Html.CheckBoxFor(m => m.IsT)
        @Html.LabelFor(m => m.IsT, "T")
    </div>
    <div>
        @Html.CheckBoxFor(m => m.IsS)
        @Html.LabelFor(m => m.IsS, "S")
    </div>
    <div>
        @Html.CheckBoxFor(m => m.IsR)
        @Html.LabelFor(m => m.IsR, "R")
    </div>              
</div>

jQuery

var cost = @Session["Cost"];
$('#chkbox').change(function (chk) {
    debugger;               
    if ($(chk).prop("checked")){
        cost = cost + 3;
    } else {
        cost = cost- 3;
    }
    $("#product").val(cost);
    $("#spProduct").text(cost);
});

Upvotes: 2

Views: 86

Answers (1)

user3559349
user3559349

Reputation:

Your element with id="chkbox" is a <div>, not a checkbox. When you use

$('#chkbox').change(function (chk) {
    if ($(chk).prop("checked")){

chk is the event, not an element (and an event does not have a checked property).

Give your checkboxes a class name and use that as a selector

@Html.CheckBoxFor(m => m.IsT, new { @class = "mycheckbox" })
@Html.CheckBoxFor(m => m.IsS, new { @class = "mycheckbox" })
....

and then the script becomes

$('.mycheckbox').change(function () {
    if ($(this).is(':checked')) {
        ....
    } else {
        ....
    }

Upvotes: 1

Related Questions