jquery id selection change class - javascript

$('#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>

Related

Better way to Find which element has a specific class from an array of elements

Suppose I have a List like the following
<ul>
<li id="slide-a" class="slide-li active-slide"><a href="#" >A</a></li>
<li id="slide-b" class="slide-li"><a href="#" >B</a></li>
<li id="slide-c" class="slide-li"><a href="#" >C</a></li
</ul>
Now , using Jquery I wanna Find out which Element has the class 'active-class'. One way would to have a nested if statement something like this:
if($("#slide-a").hasClass('active-slide'))
{
active = 'slide-a';
}
else
{
if($("#slide-b").hasClass('active-slide'))
{
active = 'slide-b';
}
else
{
if($("#slide-c").hasClass('active-slide'))
{
active = 'slide-c';
}
}
}
My question is if there exists any way to optimize the code above. Is there a generic way to achieve this such that even if I add 10 more li's in the ul the code just works fine without any modification.
Maybe just
var active = $(".active-slide").attr("id");
Demo
Use Attribute starts with selector and .each(). Try this:
$(document).ready(function(){
$('li[id^=slide]').each(function(){
if($(this).hasClass('active-slide'))
alert($(this).attr('id'));
});
});
DEMO
If you have more than one li with classactive-slide use this:
$(document).ready(function(){
var idVal = [];
$('li[id^=slide]').each(function(){
if($(this).hasClass('active-slide'))
idVal.push($(this).attr('id'));
});
console.log(idVal);
});
DEMO
You could a use jQuery $.each() on the ul to iterate through.
fiddle coming in a second.

Toggle css class using Jquery

I have a standard ul-based CSS navigation menu. I'm trying to use Jquery to toggle the active menu css class name. However, I'm encountering two issues:
The window.location.href never equals any of my anchor hrefs. I switched to pathname, but they still do not match each other. Even though in the debugger they appear to.
I cannot seem to get the li from it's anchor.prev. I need to change the class name on the li.
Here's the html:
<div id="left-content">
<ul>
<li class="separator">Main
<ul>
<li class="active link">Main 1</li>
<li class="link">Main 2</li>
<li class="link">Main 3</li>
</ul>
</li>
<li class="separator">Tools
<ul>
<li class="link">Tools 1</li>
</ul>
</li>
</ul>
</div>
When an anchor is clicked, it's corresponding li should have "active link" as the class name. And all other li's should be reset to just "link" as the class name.
Here's the Jquery javascript:
function toggle_active_menu() {
$('#left-content a').each(function() {
/*var isActive = $(this).attr('href') == window.location.href;*/
var active = this.pathname == window.location.pathname;
var prev = this.prev();
alert("active: " + active + "\nthis.pathname: " + this.pathname + "\nwindow.location.pathname: " + window.location.pathname + "\nprev: " + prev);
prev.toggleClass('active', active);
});
}
I put the alert in there to help debug. As I mentioned, the clicked anchor's href (or pathname) never matched the window's location href (or pathname). And prev is always undefined instead of being the li of the anchor.
Eventual Answer
After testing the various answers, I fould that I had to remove the onclick calls and call the toggle_active_menu function in the document ready function instead. The window location was not being updated before onclick was being called. Also, I did not use toggleClass so that I could preserve the order of the class names.
function toggle_active_menu() {
$('#left-content ul li ul li a').each(function() {
var pathname = window.location.pathname == '/' ? '/main1' : window.location.pathname;
var active = pathname.indexOf(this.pathname) != -1;
if (active) {
$(this).parent().attr('class', 'active link');
} else {
$(this).parent().attr('class', 'link');
}
});
}
To get the li which is the parent of a element use parent method and toggleClass take only the calss to toggle. To compare the href of the anchor with window.location.href you can use indexOf method.
function toggle_active_menu() {
$('#left-content a').each(function() {
var isActive = (window.location.href.toLowerCase().indexOf($(this).attr('href')) != -1);
$(this).parent().toggleClass('active');
alert("active: " + isActive);
});
}
Simplified version for you.
$('.link').click(function(){
$('.link').removeClass('active');
$(this).addClass('active');
})
toggleClass only takes one paramater it should be
prev.toggleClass('active');
To fix getting a handle on the correct LI to toggle the class, try
var prev = $(this).parent();
For the pathname, try using $(this).attr("href") and matching it against window.location.href, or checking if it's contained within window.location.href

which <li> element was clicked?

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.

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