0

Is there any ways to catch click on input, only if type of input set to checkbox? Note: I need to catch click without using any classes or id's.

I've tried following:

$('input').on('click', function(){   
    if($(this).attr('type','checkbox')){
           alert("checkbox clicked");
        }
});

Well, this is not working and I don't know any other ways. JSFiddle: http://jsfiddle.net/x8utn/

4
  • if($(this).attr('type') == 'checkbox') Commented Jun 17, 2014 at 11:32
  • 1
    You are using attr as setter which returns an object, a truthy value, you are not comparing. Commented Jun 17, 2014 at 11:33
  • +1 exactly what @undefined said! (I'm bad with words this time in the morning) Commented Jun 17, 2014 at 11:34
  • change to this: if($(this).is(':checkbox')){ Commented Jun 17, 2014 at 11:41

4 Answers 4

1

your jquery would be

$('input:checkbox').on('click', function(){   

           alert("checkbox clicked");
}); 

Demo

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

Comments

0

USe like this

$('input[type="checkbox"]').on('click', function(){ 

Fiddle

Or you can use like

$('input[type="checkbox"]').click(function(){ });

Comments

0

your not using type attr in your if condition properly. Also you can use this way :

$('input').on('click', function(){ 
    if($('#check').is(":checked"))
        {
           alert("checkbox clicked");
        }
}); 

Fiddle: http://jsfiddle.net/x8utn/2/

Comments

0

Error in your code :

$(this).attr('type') == 'checkbox' : get attribute and not $(this).attr('type','checkbox') : set attribute.


$('input') will bind click event to all input elements.

Demo

Use attribute selector [attr="value"]

$('input[type="checkbox"]').on('click', function(){..})   

Or pseudo selector :checkbox

$(':checkbox').on('click', function(){   })

Side Note : Prefer using change event on input elements.

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.