Reputation: 9074
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
Reputation: 22246
<a href=# onclick="paginationlabelclicked(this.parentNode); ">
...
function paginationlabelclicked(el){
alert(el.id);
// your code
}
Upvotes: 0
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
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
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>
<a href="#"> 2 </a>
<a href="#"> 3 </a>
<a href="#"> 4 </a>
<a href="#"> 5 </a>
</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
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