Question

I have a SQL database that PHP is getting the contents of. It gets the info from each row of a table and displays it on a web page. There is also an anchor and a hidden div containing more details from that row of the SQL table. When the use clicks the anchor the jQuery needs to detect it and show the hidden div. The problem I have is that each anchor and hidden div have a dynamic id of:

'ev_a_' . $row['id']
'ev_' . $row['id']

the jQuery I assume needs to look something like this:

$('#ev_a_')[].click(function(){
    $('#ev_')[].show();
}

I'm not entirely sure how this works and I've never used dynamic ids before in jQuery. Any suggestions?

I should point out the PHP/SQL code is:

while($row = mysql_fetch_array($q_result)){
    echo "<br/><b>" . $row['a'] . "</b><br/>" . $row['b'] . ", " . $row['c'] . "<br/>" . $row['d'] . "<br/><a class='ev_event_a'>More Details</a><br/><div class='ev_event'>" . $row['e'] . "</div>";
}
Was it helpful?

Solution

I would use a class instead for these links instead and set the ID in a data attribute. Depending on your needs you don't even need the ID as you can show the next element if it is already part of the DOM.

A simple example (ID not used...):

<a href="#" class="show_more" data-id="xx">Toggle details</a>
<div class="initially_hidden">
  ...
</div>
....
<a href="#" class="show_more" data-id="x">Toggle details</a>
<div class="initially_hidden">
  ...
</div>
....

and the javascript:

$('.show_more').on('click', function(e) {
  e.preventDefault();
  $(this).next().slideToggle();
  // if you need the ID, you can get it via $(this).data('id')
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top