0

I'm having a problem with a check box in a electron app that i've been building.

the check box was working well and returning the correct values, when checked returns true value, and false when not.

when i added some libraries to my app the check box started returning false value when checked or unchecked.

Here are the properties of the project:

Package.Json

"dependencies": {
    "dexie": "^2.0.4",
    "electron-titlebar-windows": "^3.0.0",
    "jquery": "^3.3.1",
    "lodash": "^4.17.10",
    "material-design-icons": "^3.0.1",
    "materialize-css": "^1.0.0-rc.2",
    "talkify-tts": "^2.1.2",
    "typeface-roboto": "0.0.54"
  },
  "devDependencies": {
    "electron": "^2.0.4",
    "electron-packager": "^12.1.0"
  }

Index.html

// First option
$('#roswitch').change(() => {
  if ($(this).prop("checked")) {
    console.log("Checked")
  } else {
    console.log("Not Checked")
  }
})

// Second option

$('#roswitch').change(() => {
  if ($(this).is(":checked")) {
    console.log("Checked")
  } else {
    console.log("Not Checked")
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="switch">
  <label>
    Off
    <input id="roswitch" value="false" type="checkbox">
    <span class="lever"></span>
    On
  </label>
</div>

I've tried both option in JQuery and both return false.

thank you

Rory McCrossan
  • 306,214
  • 37
  • 269
  • 303
Moha_a_Osman
  • 126
  • 1
  • 15
  • 2
    The problem is because you're using an arrow function in the event handler definition. This means that the outer scope is retained in the handler, so `this` is not what you expect it to be. Simple fix, don't use arrow functions here, or use `event.target` instead. – Rory McCrossan Sep 03 '18 at 08:26

1 Answers1

2

You have incorrect syntax while attaching change event. Due to which change event is returning the checked state value when event is attached and not when state is changed. it should be:

 $('#roswitch').change(function(){
  if ($(this).prop("checked")) {
    console.log("Checked")
  } else {
   console.log("Not Checked")
  }
})

// First option
 $('#roswitch').change(function(){
  if ($(this).prop("checked")) {
console.log("Checked")
  } else {
   console.log("Not Checked")
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="switch">
  <label>
    Off
    <input id="roswitch" value="false" type="checkbox">
    <span class="lever"></span>
    On
  </label>
</div>
Milind Anantwar
  • 77,788
  • 22
  • 86
  • 114