Ciaran
Ciaran

Reputation: 177

jQuery variable selector

I'm trying to implement a jQuery AJAX script to open a link in a div. Only thing is the links are created dynamically using a PHP while loop, shown below:

<a id="topic<? echo $rows['id']; ?>" href="viewTopic.php?id=<? echo $rows['id']; ?>"><? echo $rows['topic']; ?></a>

The following code is the jQuery I am trying to use to create the ajax function. How can I create a dynamic selector like I have illustrated with PHP in the jQuery?

<script type="text/javascript" language="javascript">
$(document).ready(function(){
$("#topic<?php echo $rows['id']; ?>").click(function(){

        $("#subConList").html(loadAni).load('viewTopic.php?id=<?php echo $rows['id']; ?>');     
    });
});
</script>

Any help would be greatly appreciated.

Upvotes: 0

Views: 663

Answers (2)

thecodeparadox
thecodeparadox

Reputation: 87073

Try this:

$('a[id^="topic"]').data('id');

Upvotes: 0

icktoofay
icktoofay

Reputation: 129099

Add a class and data-id to your rows:

<a id="topic<? echo $rows['id']; ?>" class="topic" href="viewTopic.php?id=<? echo $rows['id']; ?>" data-id="<? echo $rows['id']; ?>"><? echo $rows['topic']; ?></a>

Then select by the class and get the ID using data:

$('.topic').click(function() {
    var topicID = $(this).data('id');
    // ...

Upvotes: 1

Related Questions