jQuery selecting and filtering elements inside a div
Asked Answered
T

4

31

I have a problem with selecting and filtering elements inside a div.

HTML :

<div id="wrapper">
    <input type="text" value="you can edit me">
    <input type="button" value="click me">
</div>

jQuery :

$("#wrapper").children().click(function() {
    alert("hi there");
});

The problem is I get alerted every time I click anything inside the div.
But my requirement is to alert only when the user clicks on the button.
I know that filtering the elements in jQuery is using :button

This is what I have tried :

$("#wrapper").children(":button").click(function() {
    alert("hi there");
});

and

$("#wrapper").children().filter(":button").click(function() {
    alert("hi there");
});

It didn't work

Anyone know how to do this?

Thar answered 27/7, 2009 at 17:22 Comment(1)
@Erwin - for future reference, avoid checking the "Community Wiki" checkbox when posting questions like this. This is a valid programming question and users should earn rep from itCalci
E
53
$("#wrapper input[type=button]").click(function() {
    alert("hi there");
});
Elwira answered 27/7, 2009 at 17:22 Comment(0)
M
1

use id for a specific button-

<div id="wrapper">
    <input type="text" value="you can edit me">
    <input type="button" id='btnMyButton' value="click me">
    <input type="button" class='btnClass' id='btnMyButton2' value="click me 2">
<input type="button" class='btnClass' id='btnMyButton3' value="click me 3">
</div>

$('#btnMyButton').click(function(){
alert("hi there");
});

For all buttons in the div, follow John's answer. Use class for some buttons-

$('.btnClass').click(function(){
    alert("all class");
});

btw, i like to put my all jquery function inside ready function like-

$(document).ready(function(){        

});
Melbamelborn answered 27/7, 2009 at 17:22 Comment(0)
S
0

Try this:

$("#wrapper > input[type=button]").click(function() {
    alert("hi there");
});
Signor answered 27/7, 2009 at 17:22 Comment(0)
S
0

How about

$("#wrapper :button").click(function() { alert("I love Imogen Poots"); });

See this

Sugarplum answered 27/7, 2009 at 17:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.