Hari Harker
Hari Harker

Reputation: 791

Jquery get id of an element on click of a common class

I am programmatically populating options to increase and decrease the value of an element and store the same in the DB table. To get a better idea, consider the following example:

<tr>
  <td id="name_1">Element 1</td>
  <td><a href="#" class="increase" id="inc_1">increase icon</a></td>
  <td><a href="#" class="decrease" id="dec_1">decrease icon</a></td>
</tr>

<tr>
  <td id="name_2">Element 2</td>
  <td><a href="#" class="increase" id="inc_2">increase icon</a></td>
  <td><a href="#" class="decrease" id="dec_2">decrease icon</a></td>
</tr>

<tr>
  <td id="name_n">Element n</td>
  <td><a href="#" class="increase" id="inc_n">increase icon</a></td>
  <td><a href="#" class="decrease" id="dec_n">decrease icon</a></td>
</tr>

Whenever I click any among the n increase / decrease icon, I need to access the value of #name_n. For which, I wrote the following function:

$(".increase").click(function(){
  var id = $(this).attr('id'); //get the id of the element that was clicked.
  console.log(id);

  var arr = id.split("_"); //split to get the number
  var no = arr[1]; //get the number

  var name = $("#name_"+no).text(); //get the required value in name_n
  console.log(name); 
 });
//replica for decrease class as well.

Problem : Every time I click any increase icon, in my console, I'm getting id as inc_1 only! So, the value of name is Element 1 always. Same happens with click function for .decrease.

I have tried with the following ways to get the id:

var id = this.id;
var id = $(this).get(0).id;
var id = $(this)[0].id;

But nothing changed. The same problem persists. What's wrong and how do I resolve this?

Upvotes: 0

Views: 1496

Answers (2)

Stavros
Stavros

Reputation: 665

You could add a more generic class on the elements you wish tou target after the click(currently #name_n) and use the .closest and .siblings methods.

html

<tr>
  <td id="name_n" class="target">Element n</td>
  <td><a href="#" class="increase" id="inc_n">increase icon</a></td>
  <td><a href="#" class="decrease" id="dec_n">decrease icon</a></td>
</tr>

js

$(".increase").click(function(){
    var name = $(this).closest('td').siblings('.target').text();
    console.log(name);
});

Here is a working demo https://jsfiddle.net/0hru2jtx/

Upvotes: 1

Zolt&#225;n Tam&#225;si
Zolt&#225;n Tam&#225;si

Reputation: 12764

Your code looks correct at first glance. Maybe there is some issue with rendering, perhaps the elements really get the same ID.

However, I would recommend a different approach for this task, without using ID's. You can achieve your goal by referencing the TD element relatively to the clicked increase/decrease button. I mean something like this.

$(".increase").click(function(){
  var $td = $(this).closest("tr").children(":eq(0)"); //get the TR's first TD

  var name = $td.text(); //get the required value in name_n td
  console.log(name); 
 });

Upvotes: 1

Related Questions