Bodoppels Bodoppels - 4 years ago 129
Javascript Question

jquery selector wont work when multiple elements

I have a little problem with my jquery selector. The jquery code works fine when I have only one list item. But when I have more than one,

have the value of the first list item. Why get I always the id of the first list item?

my html and foreach loop:

<ul data-role="listview" id="uItem1" data-inset="true">
<?php foreach ($result as $keyres => $rowres): ?>

<li><a class="chat" id="<?php echo $rowres['id']; ?>" href="accept.php">chat</a></li>

<?php endforeach; ?>

my jquery:

$("#uItem1 > li > a").click(function() {
var chatid = $("#uItem1 > li > a").attr('id');

$.ajax({ url: 'read.php',
data: {chatid},
type: 'POST',
success: function(output) {
// alert(output);


Answer Source

you need to use $(this)

var chatid = $(this).attr('id');

and while you use foreach in php to generate elements maybe you will need

$("#uItem1").on('click',' > li > a',function() {

And as @Rory mentioned in comments you can use

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download