-2

I have a div containing other div elements which all contain an anchor tag that runs a javascrip function (uses AJAX to delete a row from a table). Example;

 <div id="container">
   <div><a id="btn" onclick="SomeFunction()">Delete</a></div>
   <div><a id="btn" onclick="SomeFunction()">Delete</a></div>
   <div><a id="btn" onclick="SomeFunction()">Delete</a></div>
   ... and so on
 </div>

I then have this Jquery code;

  $("#btn").click(function() {
    $(this).parent("div").fadeOut();
  });

that should fade out each of the elements on click to my knowledge, but it's only fading out the first element, if i click the next elements button's nothing happens.

I don't have extensive JQuery knowledge to understand why this is happening.

2 Answers2

5

Ids must be unique, use classes instead.

Ids

[...] elements can only have one single ID defined through the id attribute. Note that an element may have several IDs, but the others should be set by another means, such as via a script interfacing with the DOM interface of the element.

classes

Classes allows CSS and Javascript to select and access specific elements via the class selectors or functions like the DOM method

Reference

Example

HTML:

<div id="container">
    <div><a class="btn" onclick="SomeFunction()">Delete</a></div>
    <div><a class="btn" onclick="SomeFunction()">Delete</a></div>
    <div><a class="btn" onclick="SomeFunction()">Delete</a></div>
</div>

jQuery:

$(".btn").click(function() // Identify classes by a dot and the class attribute value.
{
    $(this).parent("div").fadeOut();
});

Working Demo


Offtopic: I recommend taking a look at .on().

Community
  • 1
  • 1
Jonast92
  • 4,964
  • 1
  • 18
  • 32
0

You can only have one element on a page with the same id. jQuery is getting confused. Use class or attribute selectors instead.

Lunster
  • 896
  • 6
  • 17