Jquery select all children within children - javascript

I'm sure this will be a simple question but I still struggle with DOM selectors in Jquery so here is a model of my html code:
<fieldset class="product-options" id="product-options-wrapper">
<ul class="options-list">
<li><a href>Item1.1</a></li>
<li><a href>Item1.2</a></li>
<li><a href>Item1.3</a></li>
</ul>
...other html items here
<ul class="options-list">
<li><a href>Item2.1</a></li>
<li><a href>Item2.2</a></li>
<li><a href>Item2.3</a></li>
</ul>
</fieldset>
Now how do I select all of the 'li a' items in both lists (or X number of lists) with class name .options-list and bind them with a click function.
Currently I have:
$('fieldset#product-options-wrapper ul.options-list > li a').bind('click', function(e) {
//code here
});
And it only gets the first options-list.
Thanks, greatly appreciated!
EDIT: If i click on a Item2.X list item first, then it will grab that options list. But as soon as I click on the Item1.x list items it disregards the second .options-list

If you are going to bind to each li element, you should bind it to the ul element instead (helps greatly with performance when there are a lot of events).
$('.options-list', '#product-options-wrapper').bind('click', function(e)
{
e.preventDefault();//In case you don't want to go to a different page
var clicked = e.target;//The href that was clicked
/* If you only want this to happen if the a tag was clicked, add the following line
if(clicked.tagName == 'A')*/
//Rest here
});

How about $('.options-list a').bind('click', function(e) { });?

You can use delegate in this case to make it even simpler. Try this
$('#product-options-wrapper ul.options-list').delegate('li > a', 'click', function(e) {
//code here
});

Your method seems sound to me. I created a test fiddle using your HTML (and an extra anchor to prove that it won't get the click added) and your JS (with minor modifications).
http://jsfiddle.net/chrisvenus/esZxH/1/
The selector you had did work but since you said you wanted the a to be a direct child of the li (or at least I read it that way) I slightly tweaked it in my version above. ARe you sure its not just your function is not doing quite what you want while executing or can you confirm that your click function isn't being run at all?

Related

How to create an event listener using JQuery?

I am new to JQuery. I know this question is a little bit confusing but, maybe this explanation might help:
I have a dynamic <li> tag generated by JavaScript with dynamic Id's, I just want to add an event listener to every new generated <li> tag. Maybe in a way like this ? I know this doesn't work.
<li id="2" onadded="createEvent()"></li> //new generated <li> tag
<li id="1" onadded="createEvent()"></li> //the 1st generated <li> tag
<script>
function createEvent(){
//event here
}
</script>
How can I achieved that ? or any possible solution? Thanks in advance.
Using $.fn.on function to bind event for parent of li , and use selector "li" for li, then your dynamic generated li elment will reponse the event. Like following:
//$(document) can be replaced by $(parentsOfLi) , .i.e: $("ul") or $("#" + idOful)
$(document).on("click", "li", function () {
//do your process here
//alert($(this).text());
//$(this).parent().append("<li></li>")
})

Multiple items with same class, how to distinguish them with jQuery?

I have a dropdown list where there are multiple items with class "dropdown" and "menu". On click event I want javascript to find the certain .dropdown that I clicked. Is it possible to implement "this" somewhere on my code and make it work?
$(".dropdown").click(function(e) {
e.preventDefault();
if ($(".menu").is(":visible")) {
$(".menu").slideUp();
$(this).find("li").children(".list").addClass("plus").removeClass("minus");
} else {
$(".menu").slideDown();
$(this).find("li").children(".list").removeClass("plus").addClass("minus");
}
});
Edited afterwards:
So this is my list (please don't pay attention to the fact that "a" is outside of "li"). So I need to find closest "menu" to "dropdown". Already tried closest, find etc. but nothing I tried did the trick. Any suggestions?
<a class="dropdown" href=""><li>Link 1 <div class="plus"></div></li></a>
<ul class="menu">
....
Within the event handling function, this will be set to the element that was clicked.
If that does not help, you should provide more information in your question.
jQuery uses CSS selectors so just do $(".dropdown > .menu") to select the first .menu following a .dropdown. or $(".dropdown .menu:first-child")
edit:
$(".dropdown").click(function()
{
var theNextMenu = $(this).next(".menu");
}

JavaScript- Unable to find and access the selected value in dropdown menu in Jquery

I'm trying to use the selected value in the dropdown menu but I don't know how to get it.
Attached code:
Cost Value: <input type="text" name="cost">
<ul id="menu">
<li>Category
<ul>
<li>Food</li>
<li>House</li>
<li>Entertainment</li>
</ul>
</li>
</ul>
<script type="text/javascript">
$(document).ready(function(){
$('li').hover(function(){
$(this).find('ul>li').stop().fadeToggle(400);
});
$("#menu").one("click", function(evt){
document.write(this.selectedText);
});
});
If you mean in your click handler, you want to assure that this within the handler is the anchor, not the #menu ul. Also, you probably want on, not one.
So:
$("#menu").on("click", "a", function(evt){
evt.preventDefault(); // So we don't follow the link
console.log($(this).text());
});
Notes on that:
I used on, not one, so that the handler isn't removed after the first click.
I prevented the default so that the link doesn't get followed and jump your page back to the top.
I used console.log rather than document.write because document.write at that point will implicitly do document.open and wipe out your page.
I used $(this).text() to get the text of the anchor.

Table made from list (<ul>,<li>), how to select a row? (:nth-child())?

I made a table out of a simple list structure:
<html>
<body>
<ul id="Column:0">
<li id="Row:0></li>
<li id="Row:1></li>
<li id="Row:2></li>
<li id="Row:3></li>
<li id="Row:4></li>
</ul>
<ul id="Column:1">
<li id="Row:0></li>
<li id="Row:1></li>
<li id="Row:2></li>
<li id="Row:3></li>
<li id="Row:4></li>
</ul>
<ul id="Column:2">
<li id="Row:0></li>
<li id="Row:1></li>
<li id="Row:2></li>
<li id="Row:3></li>
<li id="Row:4></li>
</ul>
</body>
</html>
Now I want to add a simple .mouseover() to every row, for e.g. changing the color of a row, when hovered. And this is what I figured out, so far:
for (var i = 2; i <= _totalRows; i++) {
var row = $('#TimeTable ul li:nth-child(' + i + ')')
row.each(function() {
$(this).click(function(evt) {
var $target = $(evt.target);
console.log($target.nodeName)
if (evt.target.nodeName == 'DIV') {
console.log(evt.parent('li'));
}
}); //end $(this).click(fn)
}); // end each(fn)
}
I get a set of all <li> objects matching to :nth-child(i) where i is the rows number.
var row = $('#TimeTable ul li:nth-child(' + i + ')')
Now I just iter this set through to add a .click(fn) to every <li>.
This works fine. Every cell has it's .click(fn) attached to it.
But the following, what to do on a click, is where I'm stuck for several hours now:
var $target = $(evt.target);
console.log($target.nodeName)
if (evt.target.nodeName == 'DIV') {
console.log(evt.parent('li'));
}
I simply don't get it to run.
You can actually ignore this gibberish, as it's just the last of several things I already tried here.
What I'm trying to do is simply select every <li> with an id='Row:X' and manipulate its CSS. The best I yet had was, that I can click a cell, but no matter in what row this cell is, the last one gets colored. I remember having used i as the row-index, when that happened, so I might miss some understanding of event-handling here, too.
Use a class name for duplicate groups of elements not an ID. If you give row one a class of "Row1" the selector is simply:
$('.Row1')
Then:
$('#TimeTable li').removeClass('highlight');
$('.Row1').addClass('highlight');
If you just wish to change the color on mouseover:
$('#TimeTable ul li').mouseover(function(){
$(this).css('background','red');
});
$('#TimeTable ul li').mouseout(function(){
$(this).css('background','green');
});
Make your ID's like so: C1R1 (Column1Row1) and so on
JQuery read/google up "jquery each"
JQuery read/google up "jquery bind click"
JQuery read/google up "jquery attr" and "JQuery val()"
This will give you the knowledge to write your own and most importantly understand it better. You will want to achieve the following (your close but no for loop required):
A list which JQuery attaches a click event handler to each LI, and then when the click happens the ID can be retrieved.
PS. There's a time and place for tables, they 9/10 times nearly always better for displaying data than CSS is. If you have a complex multi column row and want fiexed hights and no JS to fix things or do anything smart you can have a table and css :Hover on TR for stying mouse over and out etc. Heights are also constant.
PS. PS. If your data is dynamic and coming from a database and the whole row is an ID from the database I tend to avoid using the html ID attribute for this and make my own. You can retrieve this via attr("myattribute");
NOTE ON CSS and IDS:
Standard practice for ID's are to be used once on a page.
Class for repeatable content
Good luck.

Swap a class of an <li> on click

I am trying to swap the selected class from tab to tab to display which one is current
Sample Code
$("li.selected").idTabs(function(id,list,set){
$("a",set).removeClass("selected")
.filter("[#href='"+id+"']",set).addClass("selected");
for(i in list)
$(list[i]).hide();
$(id).fadeIn();
return false;
});
so on click I am trying to remove and load the selected class with no luck, tried this
<ul class="idTabs">
<li class="selected">Request more information</li>
<li>Request a test drive</li>
<li>Make an offer</li>
<li>Get a quote</li>
</ul>
$('.idTabs li').click(function(){
$('.idTabs li').removeClass('selected');
$(this).addClass('selected');
return false;
});
Aaron, your second example seems like it should work, but only works on the first two list items for some reason. I added classes to the li's to make the selector more specific and it works fine now.
<ul class="idTabs">
<li class="navTab selected">Request more information</li>
<li class="navTab">Request a test drive</li>
<li class="navTab">Make an offer</li>
<li class="navTab">Get a quote</li>
</ul>
$('.navTab').click(function(){
$('.navTab').removeClass('selected');
$(this).addClass('selected');
return false;
});
Regarding your comment below:
It works every time when you click on an li... does not work when clicking on the anchor text because the click handler is not attached to that. You should add "display: block;" to your anchor within your li to expand the click area to the entire li (you will need to remove the padding from your li and in turn pad your 'a' so that the entire li is clickable). then... move the click handler to the anchor and have it change the parent's (li) class. I'm thinking it should go something like this (I'm not able to test it out right now):
$('.navTab a').click(function(){
$('.navTab').removeClass('selected');
$(this).parent().addClass('selected');
return false;
});
Give all your tabs a class like 'tab', then try something along the lines of this:
$('li.tab').click(function(){
$('.tab').removeClass('slected');
$(this).addClass('selected');
return false;
});
You haven't really said what the problem is, but I'm guessing your selectors aren't quite right. You seem to be passing in the "set" class as a second argument, rather than as part of the selector string.
Try:
$("a," + set).removeClass("selected")
and
.filter("[#href='"+id+"']" + set)

Categories