0

I am using the following html

<div id="chatid" name="1">
  <img src="http://placehold.it/50/55C1E7/fff" alt="User Avatar" class="img-circle" /> John
</div>
<div id="chatid" name="2">
  <img src="http://placehold.it/50/55C1E7/fff" alt="User Avatar" class="img-circle" /> James
</div> 

I am using the following jquery script

$(document).ready(function() {
  $("#chatid").click(function() {
    thread = $(this).attr('name');
    $("#chatmessages").load('fetchmessages.php?id=' + thread);
    //alert($(this).attr('name'));
    return false;
  });
});

This only gives the name when clicking on the first "chatid" Div, is there a way for me to return the name of any "chatid" Div?

Thanks

vamsikrishnamannem
  • 4,817
  • 5
  • 23
  • 34
user813813
  • 323
  • 1
  • 8
  • 28
  • 3
    Not sure if it's just for the sake of example but it's a bad idea to have multiple `id` attributes with the same name. – sbeliv01 May 18 '15 at 17:55
  • You've got invalid HTML, please validate your HTML with this validator: https://validator.w3.org/#validate_by_input HINT: You use 2 times the same ID, this causes to 'crash' your CSS & JS – Jonas Libbrecht May 18 '15 at 17:58
  • `id` is Unique don't use repeatedly. Replace id as a class and `thread` declare it `var thread`.... – vamsikrishnamannem May 18 '15 at 17:58

3 Answers3

8
$('div').click(function(){
    alert($(this).attr('name'));
});

Additionally, do not use the same ID for multiple elements as this is bad practice. Use classes instead.

See Why is it a bad thing to have multiple HTML elements with the same id attribute?

Community
  • 1
  • 1
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
3

You have invalid html. There can be only one element with given id.

Use class instead:

<div class="chatid" name="1">

then your selector will be:

$(".chatid").click( //do something );
n-dru
  • 9,285
  • 2
  • 29
  • 42
1

id is unique don't use repeatedly

<div class="chatid" name="1">
  <img src="http://placehold.it/50/55C1E7/fff" alt="User Avatar" class="img-circle" /> John
</div>
<div class="chatid" name="2">
  <img src="http://placehold.it/50/55C1E7/fff" alt="User Avatar" class="img-circle" /> James
</div>

JavaScript is

    $(document).ready(function() {
  $(".chatid").click(function() {
    var thread = $(this).attr('name');
    //$("#chatmessages").load('fetchmessages.php?id=' + thread);
    alert($(this).attr('name'));
    return false;
  });
});

Working example is Here

vamsikrishnamannem
  • 4,817
  • 5
  • 23
  • 34