sqlchild
sqlchild

Reputation: 9074

get element id using javascript

How to know which HTML element is clicked using javascript and get its ID?

I have displayed 3 labels dynamically using PHP for pagination- Page 1 , 2, 3 ,

<label id="<?php echo 'labelofpagination'.$z; ?>" value="<?php echo $z; ?>" >
<a href=# onclick="paginationlabelclicked(); "><?php echo $z; ?>
</a>
        </label>

Now i want that if 1 is clicked then 1-10 records are displayed , if 2 , then 11-20 and so on.For this i would run a MySQL query accordingly.

But how do i get the ID ,

Upvotes: 0

Views: 4187

Answers (5)

James
James

Reputation: 22246

<a href=# onclick="paginationlabelclicked(this.parentNode); ">

...

function paginationlabelclicked(el){
  alert(el.id);
  // your code
}

Upvotes: 0

Quentin
Quentin

Reputation: 944202

Build on things that work. Start with a working link.

<a href="myScript.php?page=$z" 
   onclick="return paginationlabelclicked(this);">
      <?php echo $z; ?>
</a>

Then your script can extract the value from the href attribute or the content.

function paginationlabelclicked(element) {
    var page = element.firstChild.data;
    // …
    return false;
}

It would be a good idea to ditch the onclick attribute too.

Upvotes: 5

Molecular Man
Molecular Man

Reputation: 22386

try pass this to handler

<a href=# onclick="paginationlabelclicked(this); "><?php echo $z; ?>
    </a>

and then you can access id by using

function paginationlabelclicked(el){
  alert(el.id);
  // your code
}

UPDATE

In order that to be working you have assign id to anchor

<a id="page<?php echo $z; ?>" href=# onclick="paginationlabelclicked(this); "><?php echo $z; ?>
    </a>

and then you can access id by using

function paginationlabelclicked(el){
  alert(el.id.replace('page', ''));
  // your code
}

Upvotes: 2

jfriend00
jfriend00

Reputation: 707926

I'm assuming, what you want to do is to get the text out of the <a> link that was clicked on so you can know what number the user clicked on and you can use that for your query. Here's a jQuery version:

HTML:

<label id="labelofpagination">
    <a href="#"> 1 </a>&nbsp; 
    <a href="#"> 2 </a>&nbsp; 
    <a href="#"> 3 </a>&nbsp;
    <a href="#"> 4 </a>&nbsp; 
    <a href="#"> 5 </a>&nbsp; 
</label>

Javascript:

$("#labelofpagination a").click(function() {
    // get text, trim string, convert to number
    var num = parseInt($(this).text().replace(/^\s+|\s+$/g, ""), 10);  
    // go to that page here
});

And a jsFiddle demo: http://jsfiddle.net/jfriend00/wesWd/

Upvotes: 0

Saeed
Saeed

Reputation: 7370

You can easily send the id into the function called onclick, something like that:

<label id="<?php echo 'labelofpagination'.$z; ?>" value="<?php echo $z; ?>" >
<a href=# onclick="paginationlabelclicked(<?php echo $z; ?>); "><?php echo $z; ?>
</a>
</label>

Upvotes: 0

Related Questions