JQuery selection buttons inside a div

I would like to select a specific group of buttons that exist inside the DIV, and assign their identifier to a hidden field on the page, but I can’t have my life choosing buttons inside the div. Example fails below

SOURCE HTML

<div id = test> <div class="ButtonGroupWrapper"> <img src="test.jpg" width="100" height="100" alt="thumbnail" /> <input id="buttonID5" type="submit" value="Link" class="button" /> </div> <div class="ButtonGroupWrapper"> <img src="test.jpg" width="100" height="100" alt="thumbnail" /> <input id="buttonID6" type="submit" value="Link" class="button" /> </div> </div> 

Jquery selector not working

  $(".ButtonGroupWrapper").find(":button").click(function () { alert("hi there"); return false; }); $("#ButtonGroupWrapper input[type=button]").click(function () { alert("hi there"); return false; }); $("#ButtonGroupWrapper :button").click(function () { alert("hi there"); return false; }); 
+7
source share
3 answers

Try:

 $(".ButtonGroupWrapper").find(".button").click(function () { alert("hi there"); return false; }); 

Your first example failed because you are trying to target the class that precedes it . not : You may also be trying to target an element of a type button, but this element is of type submit.

The second example failed because you are trying to select the type button input when it does not exist (your goal is the submit type). An alternative would be input[type=submit] .

Your third example is not suitable for the same reason as the first example if it is looking for an element of a type button.

See also http://api.jquery.com/button-selector/

+10
source

A space is searched for the .button class in your .ButtonGroupWrapper class. (NOTE: not some kind of 'button', but everything added to the class = "button" code)

 $(".ButtonGroupWrapper .button").click(function () { alert("hello"); return false; }); 

In your HTML code, the input for the view has a 'class' of 'button'. Actually it can be anything, for example .strawberry or .mybutton or anything.

Alternative:

Since you have an identifier that wraps the entire batch, you can also click the button in the identifier:

 <div id ="test"> <div> <img src="test.jpg" width="100" height="100" alt="thumbnail" /> <input type="submit" value="Link" class="button" /> </div> <div> <img src="test.jpg" width="100" height="100" alt="thumbnail" /> <div class="button" />Just text</div> </div> </div> 

And then your javascript could be:

 $("#test .button").click(function () { alert("button class clicked"); return false; }); 

Remember that you need to run this after loading the DOM, so it’s best to either write it at the end of the page or wrap it in your favorite onready function.

+7
source

This will work:

 $(".ButtonGroupWrapper").find(".button").click(function () { alert("hi there"); return false; }); 
0
source

All Articles