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();
});
Related
I am currently developing a program. It includes a 3 option navigation bar. It uses <li> and does not have id's, when i try to add id's to them it messes up the order, and doesent even work with a click! Im starting to loose faith with it.. can anyone help me on this one,
my GOAL is to have it alert different things on different clicks, so than I could link different html pages,
fiddle used HERE.
<ul class="ui-module menu-selector" id="menu-selector">
<li>Home</li>
<li class="js-is-active">Notif's</li>
<li>Profile</li>
</ul>
Since you don't have ids, I suppose that childNodes property will help a lot.
For example, you can use:
var lis = document.getElementById('menu-selector').childNodes;
// or you can select lis directly...
// var lis = document.querySelectorAll('#menu-selector li');
Array.prototype.slice.call(lis)
.forEach(function(li) {
// do something... like
li.onclick = function () {
console.log(this);
}
});
Note: childNodes (or querySelectorAll return) is NodeList type, and I use Array.prototype.slice.call() in order to use forEach() method on it.
See childNodes for more details.
if you don't want to have ids on your li elements for some reason you can use the following logic to select active li:
$("#menu-selector li.active").on("click", function(){
alert($(this).text())
});
I added id's for you, not sure what you meant by it messing up the order.
HTML
<div class="ui-items">
<header class="ui-module app-header">VoiceBox <i class="entypo-user-add"></i>
<i class="entypo-pencil"></i>
</header>
<div id="outer">
<ul class="ui-module menu-selector" id="menu-selector">
<li id="home_li">Home</li>
<li id="notif_li" class="js-is-active">Notif's</li>
<li id="profile_li">Profile</li>
</ul>
</div>
</div>
Javascript
var listItem = $('#menu-selector > li');
$(listItem).click(function() {
$(listItem).removeClass('js-is-active');
$(this).toggleClass('js-is-active');
});
$('#home_li').click(function(){
alert('home clicked')
})
$('#notif_li').click(function(){
alert('notifs clicked')
})
$('#profile_li').click(function(){
alert('profile clicked')
})
Fiddle http://jsfiddle.net/1swep9oq/2/
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.
I m new to jquery. My requirement is to pass rowid(unique id of each record of a table) in a jquery function. I can get rowid only at runtime. so how can I bind click event to the tag whose id is this rowid.
Upd
Del
$(what to pass here).bind('click',function(ev) {
_operation(para1,para2); // function which is going to perfom action
ev.preventDefault();
return false;
});
get the id , and acording to id do what ever you want
$('a').on('click',function(){
var id = $(this).attr('id');
if(id == //what you want)
{
//function 1
}
else
{
//function 2
}
return false;
});
If there are any similarities between the IDs, you can use one of the attribute selectors such as:
ID contains
$('[id*="something"]')
ID begins with
$('[id^="something"]')
http://api.jquery.com/category/selectors/
A better approach would be to place all of the dynamically named anchors into a container, and then select on that:
<div id="container">
<a ...></a>
<a ...></a>
</div>
Then you would select all the child anchors:
$('#container > a').click(...);
It's hard to find a good selector from so few HTML code. Use a class on your markup if possible:
<a class="roww" href="javascript:void(0)" id="`string(rowid(Gatepass))`">Upd</a>
<a class="roww" href="javascript:void(0)" id="`string(rowid(Gatepass))`">Del</a>
then you can use $('.roww') to query your nodes.
Here's what you can do to get the id from the event handler:
function( ev ) {
//wrap the element with jQ:
var jel = $(this);
//Then access attributes with .attr() getter:
var id = jel.attr('id');
... //do whatever you want now.
... // there's a quicker alternative to get the id without jQuery, simply:
... // var id = this.id
}
if the id comes dynamically from the server, put inside the function the same id + hash for id selctor
$(what to pass here) => $("'#" + string(rowid(Gatepass)) + "'")
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.
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");
}
});