1

I am trying to build a jQuery when clicked on div #toggle, span inside div will show and when set to toggle mode, but when I use two or more div blocks, it only shows the first span. please help.

$(document).ready(function() {
  $("div#toggle").click(function() {
    $("#show").toggle();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='toggle'>this clicked
  <span id='show'><p>Show this</p></span>
</div>
<div id='toggle'>
  <span id='show'><p>fhslkjklsfjl</p></span>
</div>
Milan Chheda
  • 8,159
  • 3
  • 20
  • 35
O.Kevin
  • 11
  • 3
  • 4
    use class as id should be unique! – Prashant Shirke Jun 05 '17 at 05:34
  • 1
    Vote to close as _This question was caused by a problem that can no longer be reproduced or a simple typographical error. While similar questions may be on-topic here, this one was resolved in a manner unlikely to help future readers. This can often be avoided by identifying and closely inspecting the shortest program necessary to reproduce the problem before posting._ – mplungjan Jun 05 '17 at 05:36
  • 1
    Or better: Duplicate of https://stackoverflow.com/questions/8498579/how-jquery-works-when-there-are-multiple-elements-with-the-same-id – mplungjan Jun 05 '17 at 05:37

3 Answers3

0

Try This :-

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id='toggle'>this clicked
      <span id='show'><p>Show this</p></span>
    </div>
    <div id='toggle'>2 nd button
      <span id='show'><p>fhslkjklsfjl</p></span>
    </div>

       $("div#toggle").click(function(e) {
  if (e.target !== this)
    return;
    $(this).find("#show").toggle();
  });

https://jsfiddle.net/9oh6yqfn/9/

Hussy Borad
  • 626
  • 5
  • 20
  • 1
    IDs should always be unique in HTML. In case you want to use same name across DOM elements, you should use class. – Milan Chheda Jun 05 '17 at 06:25
0

You can not use same id. ID should be unique.

Try by giving class:

  $(".toggle").click(function(e) {
  if (e.target !== this)
    return;
    $(this).find("#show").toggle();
  }); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='toggle'>this clicked
  <span id='show'><p>Show this</p></span>
</div>
<div class='toggle'>2 nd button
  <span id='show'><p>fhslkjklsfjl</p></span>
</div>
Juhi
  • 270
  • 2
  • 17
-1

You cannot have same id for both spans. Try using different id's for span. For eg:

$(document).ready(function() {
  $("div#toggle").click(function() {
    $("#show").toggle();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='toggle'>this clicked
  <span id='show'><p>Show this</p></span>
</div>
<div id='toggle'>
  <span id='show1'><p>fhslkjklsfjl</p></span>
</div>
Pritam
  • 3
  • 5