2
  • Windows 7
  • VisualStudio 2015
  • C# .Net MVC
  • jquery 3.1.1

I must be missing something trivial. I have a checkbox and on it I set a data element that holds the "id" number (index) of the item. I have the on change method below

 1      $("input#item_IsHere").on("change",
 2          function () {
 3              var index = $(this).data("index");
 4              var checked = $(this).checked === true ? 1 : 0;
 5
 6              console.log("on change: " + $(this).checked);
 7              //...
 8          });

When I click the checkbox the change method fires and index is set as I expect. What I didn't expect is that the checked property of $(this) would be undefined.

I have also tried a fiddle for this but the fiddle worked :/

I am seeing this in Chrome and Firefox. When the page loads I see the checkbox and bring up the developer tools debugger. In the debugger I set a breakpoint on the console.log (lise 6). When I click the checkbox it runs to the breakpoint and waits. I can hover over the first $(this) (line 3) and I can see that the checked property is set to true in this case.

The issue is that the value of var checked ends up being 0 and the result of the console.log is

    on change: undefined

Oh, I've also done the ternary operator on line 4 as

    var checked = $(this).checked ? 1 : 0;
and
    var checked = $(this).is(":checked") ? 1 : 0;
and
    if ($(this).checked) {
        checked = 1;
    } else {
        checked = 0;
    }

with the same results.

What am I not seeing?

Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87
7 Reeds
  • 2,419
  • 3
  • 32
  • 64

1 Answers1

2

You should use $("input").is(":checked")

var checked = $("input:eq(0)").is(":checked") ? 1 : 0;

console.log(checked);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="checkbox" checked />
Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87