2

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);
});
12
  • did you debug and see what is the value of 'chk'? i suspect $(chk).prop("checked") is not true alwys Commented Apr 10, 2018 at 21:49
  • What is $(chk)? that would return undefined and you will always execute the if block Commented Apr 10, 2018 at 21:50
  • 1
    I assume you want if ($(this).is(':checked') { - but you have not even indicated what the element with id="chkbox" is Commented Apr 10, 2018 at 21:51
  • @StephenMuecke, it is always executing else statement. chk gives me the selected checkbox. Commented Apr 10, 2018 at 21:54
  • @user9405863, Yes it is not always true. Why it is happening like this? Please suggest me. Commented Apr 10, 2018 at 21:56

1 Answer 1

1

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 {
        ....
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.