-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>

5
  • 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. Commented Nov 8, 2018 at 9:13
  • Its not popping up alert box when i check the checkbox. Not even your corrected code for me (I ran the snippet). Commented Nov 8, 2018 at 9: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 Commented Nov 8, 2018 at 9:18
  • I have expanded this question. Should I open a new thread? Commented Nov 8, 2018 at 9: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. Commented Nov 8, 2018 at 9:25

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.