How to find the list <li> number using jQuery? - javascript

I want to find the order of the <li> the user has clicked. For eg.,
<ul>
<li id="li1">This is list one</li>
<li id="li2">This is list Two</li>
<li id="li3">This is list three</li>
</ul>
When the user clicks on the list item 2, then I had to retrieve the id of that item as li2. How to achieve this?

As pointed out below there are a couple of ways to add the event handlers. .bind is one, .click another. You can also create the function with your logic separately and refer to it in you bind or click event attachment.
<script type="text/javascript">
// version 1 with bind
$(function(){
$("li").bind("click", function(){alert(this.id);});
})
</script>
<script type="text/javascript">
// version 2 with click and the separated method
$(function(){
$("li").click(listClickHandler);
})
function listClickHandler(){
alert(this.id);
}
</script>
separating your handler methods from your handler assignments makes a lot of sense when you are assigning event handlers on the fly or at different points in the page life cycle. The reason I use bind more often then click is that bind can be used for a lot of different events so it would be easy to imagine creating an event assignment factory:
<script type="text/javascript">
// version 3, event assignment factory
function assign(selector, event, method){
$(selector).bind(event, method);
}
$(function(){
assign(".menu li", "click", listClickHandler);
assign(".menu li", "mouseover", listHoverHandler);
})
function listClickHandler(){...};
function listHoverHandler(){...};
</script>
hopefully this is more then you will ever need.

Assuming there are just these li items on the page, the following would alert the id of the li if the user clicks on it.
<!-- on the side: you could leave out the type attribute, when using HTML5 -->
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$("li").click(function(){
alert($(this).attr("id"));
});
});
</script>
More on click: http://api.jquery.com/click/
Mode on attr: http://api.jquery.com/attr/

Alternatively to Gabriels answer:
$("li").click(function(){
alert($(this).attr('id'));
});

$('li').click(function(){
alert(this.id);
}​);​
There is no need for an extra $()-function call: this.id works as well.

you might need to loop through your li list. I think you want to generate li ids depending on their index relative to the parent ul. right? you can that with following code
$("ul li").each(function(index, node){
$(this).click(function(){
alert("You clicked on li"+index);
});
});
See this http://www.jsfiddle.net/w9qpj/1/ for live example.
For fetching index of particular li you can use jQuery index function http://api.jquery.com/index/.
or for fetching li using its index you can use jQuery eq function http://api.jquery.com/eq/
$('ul li').eq(2).css('background-color', 'red');
Above code will make ul's 3rd li element's bacground color red.

Related

Elements appeneded not triggering events

I have a list
<ul id="list">
<li> element one <span class="remover">X</span></li>
<li> element two <span class="remover">X</span></li>
</ul>
and this list is dynamically appended with
<input type="text" id="adder">
<button id="add">Add</button>
<script>
$("#add").click(function(){
$("#list").append('<li>'+$("#adder").val()+' <span class="remover">X</span></li>');
});
</script>
but the problem is this with part
<script>
$(".remover").click(function(){
$(this).parent().remove();
});
</script>
The remove works perfectly with the static added items, but when it comes to the new appended items nothing happens on click, doesn't even trigger the function
I'd suggest:
$('#list').on('click', '.remover', function(e){
$(this).parent().remove();
});
JS Fiddle demo.
References:
on().
parent().
remove().
Call the click function on list and set remover as target like so:
$( '#list' ).on( 'click', '.remover', function (e) {
$(e.target).parent().remove();
});
You can't set a click event directly on it, it has to be set on the element that never is added to the page.
you should use
on('click',function(){})
not
.click()
refer to : http://api.jquery.com/on/
as click will relate to current item within document , while on is related to future items that will be added to document , however you should always use on with something that already exists in your document like for example the parent of the future added element so use something like
$("#parent").children("li").children('.remover').on("click",function(){bla bla bla;});

How to create click event for specific link in a jQuery listview.

I'm trying to create a function that starts when you click on a specific link in a listview.
The issue is that event doesn't seem to fire when you click the link. The list is created dynamically. I'm not sure if that causes an issue.
<label for="listviewForLastTenCalls">Last Ten Calls:</label>
<ul data-role="listview" id="listviewForLastTenCalls">
</ul>
<script>
$('#listviewForLastTenCalls li').click(function(){
//alert('click event handler fired');
</script>
Demo
<ul data-role="listview" id="listviewForLastTenCalls">
<!-- items dynamically generated -->
</ul>
JS
$(document).on('click', '#listviewForLastTenCalls li a', function () {
// code
});
The issue is you are adding the click listener after you have created the list. When you first create the listener there is nothing for it to listen to. You need to add the on click event after you add the <li>
$('#listviewForLastTenCalls li a').click( function () {
// code
});
I hope this is not your fully markup,...
<label for="listviewForLastTenCalls">Last Ten Calls:</label>
<ul data-role="listview" id="listviewForLastTenCalls">
</ul>
<script>
$('#listviewForLastTenCalls li').click(function(){
//alert('click event handler fired');
}); //<--
</script>
And if the list is creadted dynamically, you have to attach the event, after list was created...
You have to do event delegation for dynamically added elements.
$('"#listviewForLastTenCalls"').on("click",'li' ,function(){
alert('triggered');
});
And why on() works ??
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().
Something like this:
$(function() {
$("#listviewForLastTenCalls li").on('click', function() { alert('clicked'); });
});

How to change a hidden value and the text of the

I am currently attempting to make a dropdown menu where selecting one of the links from the menu will change the hidden value as well as the text of the hyperlink. This is based upon Twitter's Bootstrap dropdown, and uses jQuery:
<div id="periodChooser" class="btn-group">
<input type="hidden" value="1" name="dtype" id="dtype1"></input>
<a data-toggle="dropdown" href="javascript:;">Weekend</a>
<ul class="dropdown-menu">
<li>Weekend</li>
<li>Week</li>
<li>Midweek</li>
</ul>
</div>
The script that I have attempted to write is as follows:
<script>
jQuery(function($){
$('#periodChooser').each(function() {
$('.dropdown-menu a').click(function() {
$('.btn-group').find('input[type=hidden]').val($(this)
.data('value')).change();
$('.btn-group').find('.btn:eq(0)').text($(this).text());
});
});
});
</script>
Unfortunately, whilst it doesn't return any specific error, the code does not work. Any suggestions?
Bind event out side each
<script>
$('#periodChooser .dropdown-menu a').click(function() {
$('.btn-group').find('input[type=hidden]').val($(this)
.data('value')).change();
$('.btn-group').find('.btn:eq(0)').text($(this).text());
});
</script>
I think that this can be optimized and made more re-usable.
First of all, you are using jQuery selectors like $('.btn-group') very ineffectively.
Secondly it will break, if you will use more than one "widget", because the context is whole document and it will find all elements with that class .btn-group.
Thirdly it would be more effective to use single event handler that is being binded to the parent <ul> element instead of each <a> element. It's called "event delegation". http://api.jquery.com/delegate/
<script>
$('#periodChooser').each(function() {
var $input = $('input', this),
$select = $('>a', this);
$('ul', this).on('click', 'a', function() {
var $this = $(this);
$input.val($this.data('value')).change();
$select.html($this.html());
});
});
</script>
I made this code available in JSBin: http://jsbin.com/welcome/38724/edit
What I did here?
<script>
$('#periodChooser').each(function() {
// Find and store input and "select" element only once.
var $input = $('input', this),
$select = $('>a', this); // This finds only direct child element <a>
// Find the <ul> element inside the #periodChooser
// Bind a click event that will "bubble up" from <a> elements that are children of it
$('ul', this).on('click', 'a', function() {
// Wrap a jQuery around the <a> element
var $this = $(this);
// Set the input value and execute "change" event(s)
$input.val($this.data('value')).change();
// Change the "select" title. Doesn't matter if you use html() or text() - choose yourself!
$select.html($this.html());
});
});
</script>
Now, you can use this to make multiple widgets inside single page! :)
<script>
$('.btn-group').each( /* Well, you know, the function goes here... */ );
</script>
Of course, threre are many other things that has to be done here, like opening and closing the "option list", scrolling and probably many other things...

jQuery on/delegate correct syntax

As the jQuery API is currently down, is anyone able to assist me with the below? I am ajax loading an unordered list into the web page and need to be able to attach hover and click events to the list items.
<ul>
<li class="option">Item 1</li>
<li class="option">Item 1</li>
<li class="option">Item 1</li>
</ul>
So far I have tried a few variations of the below jQuery code using .on for version 1.7+
$("ul").on("click", "li .option", function(){
alert($(this).text());
});
Can anyone point me in the right direction? I'm aware that .live has been deprecated and that .delegate has been superseded so really only looking for a solution that will allow me to use .on.
Not li .option, because it find element within li with class option, but you have this class to li, so it will be li.option or .option.
So for .on(), it looks like:
$("ul").on("click", "li.option", function(){
alert($(this).text());
});
But for .delegate(), it looks like:
$("ul").delegate("li.option", "click", function(){
alert($(this).text());
});
According to you edit
you're trying to bind click to li.option with container reference ul, which is also append to DOM alter. So you can go for #content, which already exists in DOM ans where you append you whole list.
So delegate event will looks like:
$("#content").delegate("ul > li.option", "click", function(){
alert($(this).text());
});

run a function when a user clicks on any list element

This is probably a very common question, but I was unable to find an answer myself;
All my list elements call the function setQuery like this
onClick="admin_stats.setQuery(this);"
rather than [hardcode] add this to every list element, is there a way to simply have it run when a list element is clicked?
I'm not very familiar with jQuery Live or binding/unbinding, but I think they would play a role here?
Before I reinvent a rather square-looking wheel I thought I might ask =)
edit: my list elements look like
<ul>
<li id="usersPerMonth" onClick="admin_stats.setQuery(this);">Users per Month</li>
<li id="statsByUser" onClick="admin_stats.setQuery(this);">Stats by User</li>
</ul>
the this.attr("id") is then used to look up what the actually SQL text looks like, from a json-style variable:
queries : {
usersPerMonth : " ... some sql ...",
statsByUser : " ... some sql ...",
...
}
so that's why I have the divs named that way (and I'm open to design suggestions)
$(function() {
$('#myList').delegate('li', 'click', function() {
admin_stats.setQuery( this );
});
});
This assumes your <ul> element has the ID myList. It will handle clicks inside of it on any <li> elements, calling your function, and passing this as the argument.
The .delegate() code is wrapped in $(function() {}); so that it doesn't run until the DOM is ready. This is a shortcut for jQuery's .ready() function.
Yes - use jQuery like this:
$('li').live("click", function(event){
admin_stats.setQuery(event.target);
});
This is assuming you want to set it to every li element. You can find the documentation for live here: http://api.jquery.com/live/
What live does makes sure that all elements passed to it will always have the click handler in the function specified.
jQuery is probably your best bet. Are you adding new elements on the fly, or will the elements be there when the attach is ready to go? If they're "satic" in the sense that once the page is loaded that's it, you could use:
$(document).ready(function(){
$('li').bind('click',function(e){ // may need to change the selector to be more specific
admin_stats.setQuery(this);
});
});
that needs to fire onClick... so:
$('li').click(function(){
admin_stats.setQuery($(this));
});
In jQuery you select elements using CSS-style selectors (can use this if more elements will not be added; this uses .click()):
$(function() {
$('#liContainer li').click(function() {
admin_stats.setQuery(this);
});
});
We put the whole thing inside $(function() { ... }); because the page needs to be ready before binding the event handler. Alternatively, you could do it like this if more elements are added. This uses .delegate():
$(function() {
$('#liContainer').delegate('li', 'click', function() {
admin_stats.setQuery(this);
});
});

Categories

Resources