which <li> element was clicked? - javascript

I have 5 (maybe more) li elements.
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>
I want to get which elements was clicked(which row??). If random user clicks Two I want to get $("li:eq(1)")(as typed).
How can I get this result?

You can use jQuery.index. Something like this:
$('ul > li').click(function() {
alert($(this).index($(this).parent('li'));
});

You can get the text node value of the clicked item with:
$('li').click(function(){
var clicked = $(this).text();
alert(clicked+" was clicked");
});

$("#ulId li").click(function() {
$(this).something(); //the clicked li is $(this), and you can invoke functions on it.
})

If you give your elements an id such as
<ul id="mylist">
<li id="el_1">One</li>
<li id="el_2">Two</li>
<li id="el_3">Three</li>
<li id="el_4">Four</li>
<li id="el_5">Five</li>
</ul>
Then you can use $(this).attr(id) in the click handler to determine the id of the clicked element. This will also allow to give non sequential ids to your elements, and will detach what's written in the <li> from the actual value you get.
Also, you can encode multiple value in the id (for instance el_5_3) which can be useful sometimes.
$("#mylist li").click(function()
{
var id = $(this).attr("id").split("_");
alert("You clicked the element with id="+id[1]);
});
Working example:
http://jsfiddle.net/jFrdp/

Working example: http://jsfiddle.net/tbugV/1/
$("#mylist li").each(function(index)
{
$(this).data("row", index);
}).
click(function()
{
alert($(this).data("row"));
});

$('html').click(function() {
var el = e.target;
alert(el);
});

As people just keep posting code, and no explanations, I will try the other way around...
The click event handler is called in the scope of the clicked element, so you can use the this keyword to access the element. You can use $(this) to get a jQuery object that contains the clicked element, so that you can use jQuery methods on it.
Example:
$(document).ready(function(){
$('ul li').click(function({
var text = $(this).text();
alert('You clicked on the item with the text "' + text + '"');
}));
});

$('li').click(function(){
alert($(this).html());
});
This code will alert one when user will click the one button.

Related

add class to the match element id from a variable

I have this html structure
<script>
$(document).ready(function(){
var active_menu = "menu2";
//here do like, add .active to the #menu2 element.
});
</script>
<ul>
<li id="menu1">menu 1</li>
<li id="menu2">menu 2</li>
<li id="menu3">menu 3</li>
</ul>
Now what I want is to add a class name named "active" to the match element id name within the active_menu variable. How to do that? I know I can use if and else statement or switch to achieve that but it will look awfully long way code implementation.
PS: to sharpen the details above, basically what I'm trying to do is add a class to the element which has an id match to the variable active_menu.
any help, suggestions, recommendations would be greatly appreciated.
$(document).ready(function(){
var active_menu = "menu2";
$('#'+active_menu).addClass('active');
});
This should do the trick
Fiddle
$(function(){
var active_menu = "menu2";
$('#'+active_menu).addClass('active');
$('#'+active_menu).find('a').addClass('active');
});
This should do the trick:
$('#' + active_menu).addClass('active')
You should do this :
$(document).ready(function(){
var active_menu = "menu2";
$('#'+active_menu ).addClass('active');
//here do like, add .active to the #menu2 element.
});
you can do this
$('#' + active_menu).addClass('active');

jquery id selection change class

$('#sidebar ul li ul li').click(function () {
var ids = $(this).attr('id');
$('#ids').addClass('active');
$('#ids').parent('ul').parent('li').addClass('has-sub active');
alert(ids); // Will alert the id if the element has one
});
I didn't understand why this is not working. alert gives me the id of the li element but the 2 lines before it don't work I mean these 2:
$('#ids').addClass('active');
$('#ids').parent('ul').parent('li').addClass('has-sub active');
Where is the problem? Am I missing something?
You need to concatenate your variable like:
$('#' + ids).
$('#ids') is looking for an element with the ID of ids. And as Blender noted in the comments, why are you doing it this way? The element you're clicking on could be referred to as simply $(this) or this. To me it might make more sense to do:
$('#sidebar ul li ul li').click(function () {
$(this).addClass('active').parent('ul').parent('li').addClass('has-sub active');
});
And you might also be able to replace .parent('ul').parent('li') with .closest('li'), but I'd need to see the HTML structure to be sure.
You are taking the id of the current element to concatenate together a selector. Instead, you can use the this keyword within the handler and use it as a reference to the clicked element. Try this:
$('#sidebar ul li ul li').click(function () {
$(this).addClass('active').closest('li').addClass('has-sub active');
});
ids is a variable which holds the id of clicked element. and in your code:
$('#ids').addClass('active');
$('#ids').parent('ul').parent('li').addClass('has-sub active');
You use ids as a string. This is not correct way. You should replace $('#ids') with $('#' + ids).
Try this:
$('#' + ids).addClass('active');
$('#' + ids).parent('ul').parent('li').addClass('has-sub active');
Did you mean to apply the new classes to the ids in the variable ids? If so you are currently applying those to elements that have the id of 'ids'. You should use the following selector: $('#'+ids).
#IshanJain #RoryMcCrossan #j08691 #EliantenHolder thank you for your response. Jquery doesnt help to solve this problem but this helper worked.
public static class HtmlHelperExtensions
{
public static string ActivePage(this HtmlHelper htmlHelper,string controller, string action)
{
string _classValue="";
string _currentController = htmlHelper.ViewContext.Controller.ValueProvider.GetValue("controller").RawValue.ToString();
string _currentAction = htmlHelper.ViewContext.Controller.ValueProvider.GetValue("action").RawValue.ToString();
if (_currentController == controller && _currentAction == action)
{
_classValue = "active";
}
else if (_currentController == controller && action.Equals(""))
{
_classValue = "has-sub active";
}
else
{
if (action.Equals(""))
{
_classValue = "has-sub";
}
}
return _classValue;
}
}
and this is from my layout page
<li class="#Html.ActivePage("Order","")">
<a href="javascript:;" class="">
<span class="icon-box"> <i class="icon-dashboard"></i></span> Sipariş Açma
<span class="arrow"></span>
</a>
<ul class="sub">
<li class="#Html.ActivePage("Order","Index")"><a class="" href="#Url.Action("Index","Order")">Sipariş</a></li>
<li class="#Html.ActivePage("Order","orderProduct")"><a class="" href="#Url.Action("orderProduct","Order")">Ürün Sipariş</a></li>
<li class="#Html.ActivePage("Order","orderCloth")"><a class="" href="#Url.Action("orderCloth","Order")">Kumaş Sipariş</a></li>
<li class="#Html.ActivePage("Order","orderAccessory")"><a class="" href="#Url.Action("orderAccessory","Order")">Aksesuar Sipariş</a></li>
</ul>
</li>

Get selectd list value in foundation dropdown

I'm using foundation drop-down
You can have a look at it here:
http://foundation.zurb.com/docs/components/dropdown.html#
I've created a dropdown with the following code
<a href="#" data-dropdown="drop1" >Date Range </a>
<ul id="drop1" class="f-dropdown large date-menu" drop-down-content>
<li id="custom">Custom</li>
<li id="today">Today</li>
<li id="yesterday">Yesterday</li>
<li id="sundaytoToday">This Week(Sun-Today)</li>
<li id="montoToday">This Week(Mon-Today)</li>
</ul>
I want to get the value/id of the selected element
I've tried like below, but it's not working
$('#drop1').click(function(){
var ss=$('#drop1').val();
console.log(ss);
});
I'm a newbie to programming any help appreciated.
Thanks in advance
UPDATE: How to close the dropdown on click?
You need .text() or .html() not .val().
.val() works with form elements like input, select, radio, checkbox etc.
$('#drop1 li').click(function(){
var ss = $(this).text(); //this refers to current element clicked here.
//to get id
var id = this.id;
console.log(ss, id);
});
“this” Keyword
here is correction
$('#drop1 li').click(function(){
var id=$(this).attr('id');//to get id of clicked element
console.log(id);
var h=$(this).text();//to get text of clicked element
console.log(h);
});
update
$('#drop1 li').click(function(){
var id=$(this).attr('id');//to get id of clicked element
console.log(id);
var h=$(this).text();//to get text of clicked element
console.log(h);
$(this).parent().fadeOut(300);
$('.open').removeClass('open');
});
as per doc, class open is added to selected element. you can get selected using:
$('#drop1').click(function(){
var ss=$('this).find('.open').html();
console.log(ss);
});

How to find the 2nd closest ancestor in jQuery?

My DOM looks something like this:
<li>
<li><a class="editEntity>Edit</a></li>
<li><a class="deleteEntity>Delete</a></li>
</li>
When the used clicks on 'Edit', I want to change the outer <li> to <li class="selected>.
I tried something like this, but this is not working:
$('li a.editEntity').live('click', function() {
$(this).closest('li').closest('li').addClass('selected');
});
Any help is appreciated.
Go up a parent:
$(this).closest('li').parent().closest('li').addClass('selected');
It wasn't working because closest starts with the current element, and so if you call it on something that matches the selector, you get back the same thing you started with.
Live example
Or you can use parents with the :eq selector:
$(this).parents("li:eq(1)").toggleClass("selected");
Note that :eq uses 0-based indexes, so :eq(1) is the second parent li.
Live example
Your quoted HTML is invalid, though (an li can't directly contain an li); I assume you meant:
<li>
<ul>
<li><a class="editEntity>Edit</a></li>
<li><a class="deleteEntity>Delete</a></li>
</ul>
</li>
...or similar.
you can use
$('li a.editEntity').live('click', function() {
$(this).parents('li').addClass('selected');
});
following my previous comment.. here's the example promised... :)
$('li').each(function(index) {
alert(index + ': ' + $(this).text());
});
Stop at the second index
Further info can be found here
http://api.jquery.com/each/
I'm using this code to add active class depending on the page. This is working 100% for multi level sub-menus of AdminLTE 3, just put this code in the footer section of your page.
var url = window.location;
const allLinks = document.querySelectorAll('.nav-item a');
const currentLink = [...allLinks].filter(e => {
return e.href == url;
});
currentLink[0].classList.add("active");
currentLink[0].closest(".nav-treeview").style.display = "block ";
currentLink[0].closest("ul.nav-treeview").closest('li').classList.add('menu-open');
$('.menu-open').find('a').each(function() {
if (!$(this).parents().hasClass('active')) {
$(this).parents().addClass("active");
$(this).addClass("active");
}
});

jQuery Remove LI from UL with a hyperlink in the LI

I have a unordered list:
<ul id="sortable">
<li id="1" class="ui-state-default">First x</li>
<li id="2" class="ui-state-default">Second x</li>
<li id="3" class="ui-state-default">Third x</li>
</ul>
I want to remove the <li> from the <ul>. I have handled the click event of the class itemDelete where I try to do a remove but I assume its not working because I can't remove the <li> as a child is calling it?
$('.itemDelete').live("click", function() {
var id = $(this).parent().get(0).id;
$("#" + id).remove();
});
What's the best approach?
Assuming you're using a recent version of jQuery:
$('#sortable').on('click', '.itemDelete', function() {
$(this).closest('li').remove();
});
closest is a little more dynamic than parent (although parent works here as well.) It gets the li that is closest to the current element, upwards in the structure.
Actually, the way you have it as of now, id is going to be undefined, because none of the li's have ids.
why not just do
$(this).parent().remove()
also, don't forget to return false.
You don't have IDs on your <li>s
How about simply
$(this).parent().remove();
What wound up working for me:
Prefix your id attributes with a string or underscore (as others have pointed out)
Since frameworks like jQuery Mobile require that ids be unique across all pages (not just in one page, I prefix with the page name, an underscore, and the numerical id that lets me access records in a database.
Instead of binding to a class or the ul control, use 'on' to bind to the li of the parent list:
$('#sortable').on('dblclick', 'li' function() {
aval = $(this).attr('id').match(/\d+/g); // only want the numbers...
id = aval[0];
name = $(this).text(); // in case you need these for a post...
li = $(this); // so we can remove it from the list after the 'this' object changes inside the ajax call...
// make an ajax call to the server
var jqxhr = $.post( "somepage.php", {name: name, id: id},
function(data) {
li.remove();
$("#sortable").listview("refresh");
},'json').fail(function() { alert("error"); });
return false; // preventDefault doesn't seem to work as well...
});
It could also be looking for the index of the elements with event
$('#sortable').on('click', '.itemDelete', function(e) {
e.preventDefault();
$(e.target.parentElement).parent()[0].remove();
});

Categories