Find the clicked li number - javascript

I have a standard list.
<ul>
<li>blah 1</li>
<li>blah 2</li>
<li>blah 3</li>
<li>blah 4</li>
</ul>
And my jQuery:
$('ul li a').live('click', function() {
var parent = $(this).parent('li');
});
What I want to find out is the parent li's position in the list of the clicked link e.g. clicking on blah 3 would give me 2, blah 4 would give 3 etc.

$('ul li a').live('click', function() {
console.log($(this).parent('li').index());
});
Will give you what you want, but keep in mind these are 0 based indexes -- ie the first line item is index 0, the last line item is 3.
jQuery index() method documentation

you can get the index of an element with jquery`s index
$('ul li a').live('click', function()
{
var index = $(this).index();
});

No need to jQueryfy this :
$('ul li a').live('click', function() {
var position = 0;
var currentNode = this;
var firstNode = currentNode.parentNode.firstChild;
while(firstNode != currentNode) {
position++;
currentNode = currentNode.previousSibling;
}
alert(position);
});

I know this is an old post, but .live is now deprecated in jQuery 1.7 and removed in jQuery 1.9.
The alternative is to use .delegate:
$('ul li').delegate('a','click', function() {
alert($(this).parent('li').index());
});

The index method should do what you want.

$(function() {
$('ul li a').live('click', function() {
var parent = $(this).parent('li');
alert(parent.prevAll('li').size());
});
});

Related

Get index of li with button click

Using JQuery I'd like to get the index of the current li that I'm on when I click the button in the tabpanel residing in this list of BootStrap tabs.
<ul id="mytabs" class="nav nav-pills nav-wizard pill-font"
role="tablist" data-tabs="tabs">
<li role="presentation" class="active"><a href="#start"
data-toggle="tab">Before We Start</a></li>
<li role="presentation"><a href="#setup" aria-controls="setup"
role="tab">Setup</a></li>
<li role="presentation"><a href="#signup" aria-controls="Signing Up"
role="tab">Signing Up</a></li>
<li role="presentation"><a href="#speed" role="tab">Shipping Speeds</a</li>
<li role="presentation">Fulfillment</li>
<li role="presentation"><a href="#product"
role="tab">Products</a></li>
</ul>
I'm going to be using a counter in the button within each tabpanel so I can go forward and back. This is my JQuery without the counter..
$(document).ready(function(){
$(":button").click(function(e){
e.preventDefault();
$('#mytabs li:eq(2) a').tab('show');
});
});
Right now it just has the index 2 but if I can find the index of the current li I'll be able to add and subtract from it to get the li I want.
I tried with this but that just returns the index of the button, which isn't what I want.
Thanks everyone, a mish mash of everyone's answer turned into this:
$(document).ready(function(){
$(":button").click(function(e){
e.preventDefault();
var index = $(this).parent().index();
var length = $('#mytabs li a').length
alert(length);
index=index+1;
$('#mytabs li:eq('+index+') a').tab('show');
});
});
Try this:
$(document).ready(function(){
$(":button").click(function(e){
e.preventDefault();
var index = $(this).parent().index();
$('#mytabs li:eq(index) a').tab('show');
});
});
You can use .index to get de index of the element what you want in an array or list. It will be return the position or -1 (if it fails finding the element/value).
You can use it like this:
$(document).ready(function(){
$(":button").click(function(e){
e.preventDefault();
var index = $('#mytabs li').index($(this));
if(index > -1){
$('#mytabs li:eq('+ index +') a').tab('show');
}
});
});
If you want to use "this", I can show you how:
$(document).ready(function(){
$(":button").click(function(e){
e.preventDefault();
var element = $(this);
});
});
If you want to add a class to the element you can use element.addClass("yourClass") to get it.
I wish it that help to you.
P.D: I recommend change your jQuery selector from :button to #mytabs li, so you can get the exact element that you has been click, or you can use element.closest("li") to get the parent li.
This should work:
$(function() {
$("li").click(function() {
var li = $(this);
console.log( li.parent().find("li").index(li));
});
});
Returns you the index of the li you clicked.

How to get index value from parent element?

I have list:
<ul class="nav">
<li>first</li>
<li>second</li>
<li>third</li>
<li>fourth</li>
</ul>
I am trying to get the index of the <li> I just clicked.
What I tried is something with index() but it doesn't work as expected.
Am I missing something?
Here is my code:
console.log($('.nav li').index());
Clicking on the 2nd <li> should return "2" (or 1, if the index is starting with 0)
This here is my click-function:
$('.nav .hasChild > a').click(function(e) {
console.log($('.nav li').index());
....
});
The "hasChild"-class is not important in my case
Try this:
$('.nav .hasChild > a').click(function() {
var indexVal = $(this).closest('li').index();
console.log(indexVal);
});
Try this-
$('.nav .hasChild > a').click(function(e) {
console.log($(this).parent("li").index());//this holds the current element reference which is clicked
}
Perhaps I am missing something with the extra classes but surely it is as simple as;
$('.nav li').click(function() {
console.log($(this).index());
});

Javascript Filter Books by Genre

So, I've got a bunch of books, all attached to one or more genres and I've got a filter box (think Amazon) so users can filter through books in their preferred genre.
<div class="books">
<div class="filter">
<ul>
<li><a class="" data-filter=".classic" href="#">Classic</a></li>
...
</ul>
</div>
<ul class="library">
<li class="book classic">Classic</li>
...
</ul>
</div>
I'm then using a bit of Javascript, so when users select a genre from the filter list, it adds a class of .hidden to all books outside that genre.
if($('.books').length){
var books = $('.books');
books.find('.filter ul a').on('click', function(){
books.find('.filter ul a').removeClass('active');
$(this).addClass('active');
var selector = $(this).attr('data-filter');
books.find('.book').addClass('hidden');
books.find(selector).removeClass('hidden');
return false;
});
}
I've got a working demo of this in action here: http://codepen.io/realph/pen/atImc
Trouble is, I can only search one genre at a time (i.e. Fantasy). I'm not able to select two genres (i.e. Fantasy and Thriller). If anyone could help me to adapt this code to do just that, I'd really appreciate it.
Thanks in advance!
UPDATE:
Added an All filter to the filter list (thanks to #epascarello for his help on this):
jQuery(document).ready(function($) {
if($('.books').length){
var books = $('.books');
books.find('.filter ul a').on('click', function(e){
e.preventDefault();
books.find('.filter ul a.all').removeClass('active');
$(this).toggleClass('active');
books.find('.book').addClass('hidden');
books.find('.filter ul a.active').each(
function(){
var selector = $(this).attr('data-filter');
books.find(selector).removeClass('hidden');
}
);
});
books.find('.filter ul a.all').on('click', function(e){
e.preventDefault();
books.find('.filter ul a').removeClass('active');
books.find('.book').removeClass("hidden");
$(this).toggleClass('active');
});
}
});
This is untested, but something like this should work
var books = $('.books');
books.find('.filter ul a').on('click', function(e){
e.preventDefault(); //Cancel the click action
$(this).toggleClass('active'); //toggle the active class
books.find('.book').addClass('hidden'); //hide all of the books
books.find('.filter ul a.active').each( //find the selected filters and loop through
function(){
var selector = $(this).attr('data-filter'); //get the attribute
books.find(selector).removeClass('hidden'); //unhide the ones that match
}
);
});

jQuery tabs add more selectors to same function

I managed to reduce my jquery tabs to this current state where I define tabs ID in variables.
Question: How to modify this code to have more IDs?
For example:
var tabsId = '#tabs1', '#tabs2', ... ;
var containerId = '#tabs-container1', '#tabs-container2', ...
JS:
var containerId = '#tabs-container';
var tabsId = '#tabs';
$(document).ready(function() {
// Preload tab on page load
if ($(tabsId + ' li.current a').length > 0) {
loadTab($(tabsId + ' li.current a'));
}
$(tabsId + ' a').click(function() {
if ($(this).parent().hasClass('current')) {
return false;
}
$(tabsId + ' li.current').removeClass('current');
$(this).parent().addClass('current');
loadTab($(this));
return false;
});
});
function loadTab(tabObj) {
if (!tabObj || !tabObj.length) {
return;
}
$(containerId).addClass('loading');
$(containerId).fadeOut('fast');
$(containerId).load(tabObj.attr('href'), function() {
$(containerId).removeClass('loading');
$(containerId).fadeIn('fast');
});
}
HTML:
<ul class="mytabs" id="tabs">
<li class="current">Tab 1</li>
<li>Tab 2</li>
<li>Tab 3</li>
</ul>
<div class="mytabs-container" id="tabs-container">
Loading. Please Wait...
</div>
Actually, I don't se a single place in your code where you need your tabIds. It works exactly the same if you just remove it.
Unique instances of the .click() event will be added to each a element either way, and you don't have to specify them by ID´s. Here is an example with tabIds removed.
http://jsfiddle.net/c7RHs/
var containerId = '#tabs-container';
$(document).ready(function () {
if ($('li.current a').length > 0) {
loadTab($('li.current a'));
}
$('li a').click(function () {
if ($(this).parent().hasClass('current')) {
return false;
}
$('li.current').removeClass('current');
$(this).parent().addClass('current');
loadTab($(this));
return false;
});
});
function loadTab(tabObj) {
if (!tabObj || !tabObj.length) {
return;
}
$(containerId).addClass('loading');
$(containerId).fadeOut('fast');
$(containerId).load(tabObj.attr('href'), function () {
$(containerId).removeClass('loading');
$(containerId).fadeIn('fast');
});
}
Otherwise, you could make an array of ID´s as suggested in another answer, but I don't think you need it.
Hope it helps!
You could use array's like
var tabIds = {'tab1','tab2'};
Then you can loop over the array elements. An alternative is to use the variables like you mentioned (comma separated) and split them. Then you can loop through them again.
see this thread for an example: Split string with JavaScript

Getting Attr (ID) of Dynamically Added <li> Element with jQuery

I'm having issues getting ID of a dynamically added list element. Which is being added with the following:
$(".detail-view button").on("click", function(){
var noItems = $("ul#cart-items li").eq(0).attr("id");
var detailID = $(this).attr('id');
var orderTitle = $("#detail-"+ detailID + " span.order-title").text();
var insertTitle = $("<li><img src=\"/assets/images/global/intra_remove_item_btn.png\" />"+ orderTitle +"</li>").attr("id", detailID);
if(noItems == "emptycart") {
$("ul#cart-items li#emptycart").replaceWith(insertTitle);
$("#lp-orderform li:even").addClass("highlight");
} else {
$(insertTitle).insertAfter("ul#cart-items li:last");
$("#lp-orderform li:even").addClass("highlight");
}
});
Which updates my original HTML from the following...
<ul id="cart-items">
<li id="emptycart">You have no items in your cart.</li>
</ul>
And updates to...
<ul id="cart-items">
<li id="6955" class="highlight"><img src="/assets/images/global/intra_remove_item_btn.png">Chicken with Garlic Sauce</li>
<li id="6966"><img src="/assets/images/global/intra_remove_item_btn.png">Hunan Shrimp with Black Bean Sauce</li>
<li id="6965" class="highlight"><img src="/assets/images/global/intra_remove_item_btn.png">Hunan Pork with Black Bean Sauce</li>
</ul>
I'm trying to get the ID of the list item when a.remove-item is clicked to remove that list element.
$("ul#cart-items").live("click", "li a.replace-item", function(){
var removeItemID = $("li a.replace-item").attr("id");
alert(removeItemID);
});
But I only seem to get a value of "undefined". Any input would be greatly appreciated. Thank you!
Update
To get id of li on clicking <a> link
$("#cart-items").on("click", "a", function(){
var removeItemID = $(this).parent("li").attr('id');
alert(removeItemID);
});
Working jsFiddle
To get just id of clicked li use
$("#cart-items").on("click", "li", function(){
var removeItemID = $(this).attr('id');
alert(removeItemID);
});
Working jsFiddle
Your li element does't have remove-item class , but a hyperlink have
If you want to detect on li item click
$("#cart-items").on("click", "li", function(){
var removeItemID = $(this).find('a').attr("class");
alert(removeItemID);
});
Working jsFiddle
else if you want to detect on a hyperlink click
$("#cart-items").on("click", "a", function(){
var removeItemID = $(this).attr("class");
alert(removeItemID);
});
Working jsFiddle
The element that you are requesting the ID from doesn't have an ID. Try this code:
$("ul#cart-items").live("click", "li a.replace-item", function(){
var removeItemID = $(this).parent().attr("id");
alert(removeItemID);
});
if jQuery 1.7 or greater you should use on instead of live like so:
$("ul#cart-items").on("click", "li a.replace-item", function(){
var removeItemID = $(this).parent().attr("id");
alert(removeItemID);
});

Categories