1

Creating a click event for an input is easy

$('input').click(function () {
                alert('adsf');
        });

But how can I be selective so that the previous code only works on type checkbox or of type button, rather than using the generic 'input' selector?

3 Answers 3

3

You can use some built-in Selectors like :checkbox and :button to find these elements easily.

$('input:checkbox').click(function () {
    alert('checkbox');
});

$('input:button').click(function () {
    alert('button');
});

There's also :radio, :submit, :text, and :input selectors, among others

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

6 Comments

input:checkbox is probably a more efficient selector, no? Your selector will query the entire DOM for if its a checkbox, whereas this will limit that search to the input elements.
:checkbox is just short hand for input[type=checkbox]
narrowing down input:checkbox is redundant, also
@yc, reading this: api.jquery.com/checkbox-selector, you're absolutely right
@yc glad to hear it :) The only reason I knew that was that I remember reading somewhere (possibly a Paul Irish blog post) that the :checkbox selector is from Sizzle, and it's a known source of inefficiency.
|
0

Check out this page in the jQuery documentation.

Comments

0
$('input[type=checkbox]').click(function(){});
$('input[type=button]').click(function(){});
//or
$('input:checkbox').click(function(){});
$('input:button').click(function(){});
//or combined, this is probably the best solution in your case
$('input:button, input:checkbox').click(function(){});

2 different approaches. Doesn't matter which one you use. Both to exactly the same. I think the best is to have both selectors together if possible in your case.

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.