J.K.A.
J.K.A.

Reputation: 7404

Get an ID on page load in jquery script

I have a PHP while loop where I am generating #id dynamically.

Example :

<?php 
$i=1;
while ($row = mysqli_fetch_array($result)): 
?>

<tr>
<td class='hashtag' id='status<?php echo $i; ?>'>status value</td>
</tr>

<?php 
$i++;
endwhile: 
?>

The status id are generating like this : status1, status2, status3 etc...

I want all these Id's in my JS code ON LOAD for displaying it into the modal dialog.

Example :

<script type="text/javascript">

$(document).ready(function(){

$("#status1");
$("#status2");
$("#status3");
.
.
and so on as per the php while loop.

});
</script>

How can I achieve this?

Upvotes: 0

Views: 219

Answers (3)

Arvind
Arvind

Reputation: 938

You could use the "Starts With" selector:

$('td[id^="status"]').each(function(index){
   alert($(this).attr("id"));
});

You can specify scope of selector in order to target main td's

Upvotes: 3

stefreak
stefreak

Reputation: 1450

I would do it like this:

Change your html

<td class='hashtag status'>status value</td>

Then the js looks like this:

$('.status').each(function(i, el){
    // the i value previously generated in php is here i += 1 if you need it
    i += 1;

    // here is your element. do whatever you want with it:
    $(el).text('I am cell ' + i);
});

Upvotes: 1

SachinGutte
SachinGutte

Reputation: 7055

$("td[id^='status']").each(function(el){
    console.log(this.id);
});

This will give you id of each element.

If you just wish to apply event or plugin, you can do it via -

$("td[id^='status']").pluginName();

or

$("td[id^='status']").on("click",function(){

});

Upvotes: 1

Related Questions