0

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.

2 Answers 2

1

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');
    // ...
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for reply, I think im getting close with this, my full jquery should look something like this then? $(document).ready(function(){ $('.topic').click(function() { var topicID = $(this).data('id'); $("#subConList").html(loadAni).load("topicID"); }); });
@Ciaran: That load part should look more like this: .load('viewTopic.php?id=' + topicID)
0

Try this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.