-1

Im trying to make checkbox fire an alert if it is checked. This is my code below. What am I doing wrong here?

var $isgdpr = $("#isgdpr").is(':checked');
if ($isgdpr) {
  alert('Checked!');
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="switch">
    <input type="checkbox" id="isgdpr" checked="checked">
</label>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Wed
  • 323
  • 1
  • 9
  • 20
  • I placed your code in a snippet, where it works absolutely fine. If you're expecting this to work when the checkbox is changed, place your code in a `change` event handler. – Rory McCrossan Nov 08 '18 at 09:13
  • Its not popping up alert box when i check the checkbox. Not even your corrected code for me (I ran the snippet). – Wed Nov 08 '18 at 09:15
  • As I stated above, it only runs on load. If you want the logic to runs when the checkbox is changed you need to wrap your code in a change event handler. See the duplicate for more information – Rory McCrossan Nov 08 '18 at 09:18
  • I have expanded this question. Should I open a new thread? – Wed Nov 08 '18 at 09:24
  • The question hasn't changed. Unless you're intending to ask about a completely different topic you don't need to open anything. Have you read the duplicate I marked yet? Or even the answer below? Both solve your problem. – Rory McCrossan Nov 08 '18 at 09:25

1 Answers1

5

Your code work on page load but if you want to run it on check/uncheck of checkbox, you should put it in onchange event handler of checkbox

$("#isgdpr").change(function(){
  if ($(this).is(':checked'))
    alert('Checked!');
});

$("#isgdpr").change(function(){
  if ($(this).is(':checked'))
    console.log('Checked!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="switch">
  <input type="checkbox" id="isgdpr">
</label>
Mohammad
  • 21,175
  • 15
  • 55
  • 84