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

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);
});

Related

Remove Select option after doing the action

I have a Select option where if I select any option related div Shows up. Upto this it's fine. But I am wanting to make something like if I select the option it will display the related div but option it self will be removed.
FIDDLE
Is this possible ? Any help will be appreciated.
JS
$(document).ready(function() {
$('#contact-location').change(function(){
var location = $(this).val(),
div = $('#' + location);
$('div').hide();
div.show();
});
});
Fixed my answer to reflect the update in the question:
$(document).ready(function() {
$('#contact-location').change(function(){
var location = $(this).val(),
div = $('#' + location);
var selIndex = $("#contact-location").prop('selectedIndex');
$("#contact-location").prop(selIndex).remove();
$('div').hide();
div.show();
});
});
http://jsfiddle.net/uwt73sj3/
var selIndex = $("#contact-location").prop('selectedIndex'); here we set the select element index to a variable we can work with later.
$("#contact-location").prop(selIndex).remove(); removed the index value from the select drop down.
You could try something like:
$(document).ready(function() {
$('#contact-location').change(function(){
$('#contact-location option').show(); //clean alls
$('option:selected',this).hide(); // hide selected
var location = $(this).val(),
div = $('#' + location);
$('div').hide();
div.show();
});
})
LIVE DEMO
Why not make things more generic at the same time?
$(function () {
$('#contact-location').change(function () {
var $this = $(this);
// show only correct location
$('div').hide(); // maybe use a class rather than hiding every <div>
$('#' + $this.val()).show();
// show only alternate options
$this.find('option').show();
$this.find('option:selected').hide();
});
});
one solution is to use click on the children of select (i.e. the options) and then hide this (which is the option). Then the value of the select still has the value of the selected option and you have to reset it manually (I used the content of the first child via the css :first-child selector but you could use anything else, too).
$(document).ready(function(e) {
$('#contact-location').children().click(function(){
var $select = $(this).parent();
var $clicked = $(this);
var location = $clicked.val(); //is the same like $select.val()
var $div = $('#' + location);
$clicked.hide();
$select.val($select.children(":first-child"));
$div.show();
});
});
I used $ before the names of some variables to indicate that these variables store jQuery objects.
You can get the selected option like this:
$("option:selected", this);
From there you can hide or remove it:
$("option:selected", this).hide();
$("option:selected", this).remove();

Add class active when clicking the menu link with Jquery

I have HTML
<div id="top" class="shadow">
<ul class="gprc">
<li>Home</li>
<li>Text1</li>
<li>Text2</li>
<li>Text3</li>
<li>Text4</li>
</ul>
</div>
and JQUERY
$(function () {
var url = window.location.pathname,
urlRegExp = new RegExp(url.replace(/\/$/, '') + "$");
$('#top a').each(function () {
if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
$(this).addClass('active');
}
});
});
The problem is that when i click on the Home link all tabs are getting active class and don't understand why. I need it for the first link to not get any active class.
I'm also looking for this solution and I have tested your code. On the first approach all links are highlighted and when I click other links it is working properly. The problem was on the home page because all links are highlighted because there is "no event been received" when the page is loaded, the code will work if you send a command or by clicking each links, theoretically. To stop this behavior, I found this code to one of the answers above, add this code and change the ".sibling()" to ".previousSibling()"
$(this).parent().sibling().find('a').removeClass('active');
".sibling()" will highlighted at the end of your links change it to ".previousSibling()" so it will go to first (Li)
$(this).parent().previoussibling().find('a').removeClass('active');
Your code will be like this:
$(function () {
var url = window.location.pathname,
urlRegExp = new RegExp(url.replace(/\/$/, '') + "$");
$('#top a').each(function () {
if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
$(this).addClass('active');
$(this).parent().previoussibling().find('a').removeClass('active');
}
});
});
Check this , this will only activates clicked tab , remove active for all and then add for the one clicked
$("#top a").click(function() {
$('a').removeClass('active');
$(this).addClass("active");
});
Check this
You may try this out. It will help you:
<script type="text/javascript">
$(function () {
$('#sidebar li a').each(function () {
var path = window.location.pathname;
if (path.indexOf('?') > 0) {
var current = path.indexOf('?');
}
else {
var current = path;
}
var url = $(this).attr('href');
var currenturl = url.substring(url.lastIndexOf('.') + 1);
if (currenturl.toLowerCase() == current.toLowerCase()) {
$(this).addClass('active');
var par = $(this).parent();
par.addClass('open');
}
});
});
</script>
You're running a foreach loop on all <a> tags within your #top div. So of course it'll add the class active to all of them.
I think what you're trying to do is this: http://jsfiddle.net/rLddf/4/
I used the click event instead.
edit switched link to Kristof Feys example - more efficient.
try this...
$(function() {
$('#yourMenu a').each(function(){
$current = location.href;
$target= $(this).attr('href');
if ( $target== $current)
{
$(this).addClass('active');
}
});
});
I came across the same issue and I found it easier to just add an additional if statement so that the function would fire on all pages except the home page which met my needs.
$(function(){
var url = window.location.pathname,
urlRegExp = new RegExp(url.replace(/\/$/,'') + "$");
$('#top a').each(function(){
if ( window.location.pathname != '/' ){
if(urlRegExp.test(this.href.replace(/\/$/,''))){
$(this).addClass('active');
}
}
});
});
You could also add in an else statement to show an active link on the homepage by targeting the link directly if required.
I think you need something like this:
$(function () {
$("#top a").click(function(e){
e.preventDefault();
$(this).addClass('active');
$(this).parent().siblings().find('a').removeClass('active');
});
});
Fiddle Demo

How can I bind a click event to the last child if the last child element changes?

Assume we're making a to-do list, How can I append a new list item whenever the last list item is clicked.
In the example code below, the fourth list item retains the click event, but I would like it to be on the last list item each time.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.js" type="text/javascript"></script>
<ul id="foo">
<li><input placeholder="One"></input></li>
<li><input placeholder="Two"></input></li>
<li><input placeholder="Three"></input></li>
<li><input placeholder="Click Me Add More"></input></li>
</ul>
<script>
$('#foo li:last-child').bind( "click", function(){
var li = $(this).clone();
$('#foo').append(li);
})
</script>
For jquery 1.7+, use this:
http://jsfiddle.net/NeQ5q/
$('#foo').on( "click","li:last-child", function(){
var li = $(this).off('click').clone();
$('#foo').append(li);
})​
Try this
$('#foo li:last-child').bind( "click", function(){
var li = $(this).clone(true);
$('#foo li:last-child').unbind( "click");
$('#foo').append(li);
})​
Instead use .on() and .off()
$('#foo li:last-child').on( "click", function(){
var li = $(this).clone(true);
$('#foo li:last-child').off( "click");
$('#foo').append(li);
})​
Check Fiddle
I was trying bind instead of live
$('#foo li:last-child').live( "click", function(){
var li = $(this).clone();
$('#foo').append(li);
})
try this: http://jsfiddle.net/xu4wc/
$('#foo').on( "click","input:last-child", function(){
var li = $(this).parent().clone();
$('#foo').append(li);
})

returning clicked li class in an ul javascript/jquery

My code (the html page):
<nav>
<ul>
<li id="homeLink">Home</li>
<li id="rekenLink">Rekenmachine</li>
<li id="bakkerLink">Parkeergarage</li>
<li id="garageLink">Bij de bakker</li>
<ul>
</nav>
The javascript/jquery behind it:
$(function () {
$("ul").click(function () {
// here I want to get the clicked id of the li (e.g. bakkerLink)
});
});
How do I do that?
Use the .on() method with signature $(common_parent).on(event_name, filter_selector, event_listener).
Demo: http://jsfiddle.net/gLhbA/
$(function() {
$("ul").on("click", "li", function() {
// here I want to get the clicked id of the li (e.g. bakkerLink)
var id = this.id;
alert(id);
});
});
Another method is to bind the event to li instead of ul:
$(function() {
$("li").click(function() {
// here I want to get the clicked id of the li (e.g. bakkerLink)
var id = this.id;
alert(id);
});
});
Use jQuery on() instead of click and pass li as selector.
$(function() {
$("ul").on('click', 'li', function() {
//Here this will point to the li element being clicked
alert(this.id);
});
});
on() reference - http://api.jquery.com/on/
$(function() {
$("li").click(function() {
alert(this.id);
});
});
edit: jsfiddle link
Handle the click event of the <li> instead of the <ul>.
You can then get this.id.
Use the event's target (The anchor that was clicked) and then grab its parent's id:
$(function() {
$("ul").click(function(e) {
alert(e.target.parentNode.id);
});
});
JSFiddle
here is one of the way to do. Make sure your using the latest jquery file.
$("ul li").on('click', function() {
console.log($(this).attr("id"));
});
You may try
$(function () {
$("li").click(function () {
var id = $(this).attr("id");
alert(id);
});
});
or
$(document).ready( function() {
$("li").click(function () {
var id = $(this).attr("id");
alert(id);
});
});

Find the clicked li number

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());
});
});

Categories