Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the index of a clicked element from an array with jquery?

How can I find the index of a clicked anchor tag from an array with jquery???

I want to search if there is an element that eqqal to clicked element, and if is true return the index of that element.

i tried with something like this but it return with -1

$('#id').click(function(){

var obj = $('a').get(0).href;
var arr = $.makeArray(obj);
var getclickedhref = $(this).get(0).href;

var clickedindex = $.inArray(getclickedhref, arr);

console.log(clickedindex);
});

please can you help me??!

like image 386
takeItEasy Avatar asked Feb 04 '12 22:02

takeItEasy


People also ask

How do you find the value of clicked elements?

The buttonPressed() callback function will have a returned event object which has all the data about the HTML element that is clicked on. To get the clicked element, use target property on the event object. Use the id property on the event. target object to get an ID of the clicked element.

How do I get the indexed button to click?

index($(this)) to get the index of the button inside the table.

What is slice () method in jQuery?

slice() method constructs a new jQuery object containing a subset of the elements specified by the start and, optionally, end argument. The supplied start index identifies the position of one of the elements in the set; if end is omitted, all elements after this one will be included in the result.

Is clicked function in jQuery?

To trigger the onclick function in jQuery, click() method is used. For example, on clicking a paragraph on a document, a click event will be triggered by the $(“p”). click() method. The user can attach a function to a click method whenever an event of a click occurs to run the function.


2 Answers

I'm not sure what all the get and makeArray stuff is for but I think you're looking for index:

Search for a given element from among the matched elements.

So given some anchors:

<a>Zero</a>
<a>One</a>
<a>Two</a>
<a>Three</a>
<a>Four</a>

you could do things like this:

$('a').click(function() {
    var i = $('a').index(this);
    // i is the index of the clicked anchor within all the anchors.
});

Demo: http://jsfiddle.net/ambiguous/YbUU7/

like image 88
mu is too short Avatar answered Oct 09 '22 04:10

mu is too short


How about this:

$('a').click(function(){
console.log($(this).index());
})
like image 29
j08691 Avatar answered Oct 09 '22 05:10

j08691