0

I am trying to check if the box is checked or not with jquery. It doesn't work but I don't get why.

If I refresh the page and keep the checkbox check, then it will echo alert.

if($("#faith").is(':checked')){
    alert('hello');
}
if($("#diet").is(':checked')){
    alert('hello');
}
<input type="checkbox" name="cureway" id="faith" value="faith" /><label for="faith">My faith</label>
<input type="checkbox" name="cureway" id="diet" value="diet"  /><label for="diet">My diet</label>
<input type="checkbox" name="cureway" id="exer" value="exer" /><label for="exer">My excercise</label>

5
  • where is those script kept.. is it in a change or some other event handler Commented Mar 26, 2015 at 5:27
  • jsfiddle.net/arunpjohny/7ec0erpw/1 Commented Mar 26, 2015 at 5:29
  • Add in document ready function Commented Mar 26, 2015 at 5:29
  • It works fine.. jsfiddle.net/rrehan/sfo45mpb Commented Mar 26, 2015 at 5:30
  • its working. what is the event that you are trying to execute this. Commented Mar 26, 2015 at 5:31

4 Answers 4

1

I think you are looking for this

$('input[type="checkbox"]').on('change', function() {
    if($("#faith").is(':checked')){
      alert('hello');
    }
    if($("#diet").is(':checked')){  
      alert('hello');
    }
});

Here is the fiddle.

https://jsfiddle.net/rrehan/sfo45mpb/1/

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

Comments

1
$('input[type="checkbox"]').on('change', function() {
  if($("#faith").is(':checked')){
    alert('faith checked');
   }
   if($("#diet").is(':checked')){  
    alert('diet checked');
   }
});

Demo

Hope this helps

Comments

1

Try with this code

$(function(){
    $('input').on('click', function(){
    if($("#faith").is(':checked')){
    alert('hello');
    }
    if($("#diet").is(':checked')){
    alert('hello');
    }
       })
})

Comments

0

Try this,

Javascript

$(document).ready(function(){
    $(".checker").change(function() {
        if ($("#faith").is(':checked')) {
            alert('hello');
        }
        if ($("#diet").is(':checked')) {
            alert('hello again');
        }
        if ($("#exer").is(':checked')) {
            alert('hello again too');
        }
    });
});

Html

<input type="checkbox" name="cureway" id="faith" value="faith" class="checker" />
<label for="faith">My faith</label>
<input type="checkbox" name="cureway" id="diet" value="diet" class="checker" />
<label for="diet">My diet</label>
<input type="checkbox" name="cureway" id="exer" value="exer" class="checker" />
<label for="exer">My excercise</label>

Added a class to the checkbox.

https://jsfiddle.net/17m8wkwf/

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.