Kermit
Kermit

Reputation: 34055

Using unique id's in div's to show/hide in jQuery

I'm having some difficulties writing code to catch the 'id' name from the to open the requested .

I have three boxes:

<div>
<h3>Box 1</h3>
<p><a id="box2" href="#">Show Box 2</a></p>
</div>

<div id="box2">
<h3>Box 2</h3>
<p><a id="box3" href="#">Show Box 3</a></p>
</div>

<div id="box3">
<h3>Box 3</h3>
<p>TBD</p>
</div>

And I am trying to catch the 'id' from the tag to open the respected with that 'id'. For example, a id="box2" will open div id="box2".

$(document).ready(function() {
$("div#" + getName).hide();
$('a#' + getName).click(function() {
    $('div#' + getName).show();
    return false;
  });
});

I'm not sure if jQuery is sensitive to single or double quotes, or if I am approaching this incorrectly. Any help is appreciated. Have an outstanding day!

Upvotes: 1

Views: 3595

Answers (2)

Valamas
Valamas

Reputation: 24729

Id must be unique. Try using a class as a selector.

$("div." + getClass).hide();

Upvotes: 0

Pointy
Pointy

Reputation: 413737

You can't use the same "id" value for more than one element on a page, period. That's what "id" means.

One way to relate one element to another is to use a "data-" attribute:

<button data-friend="something">Click Me</button>

<div id='something'> ... </div>

The jQuery library will give you the value of a "data-" attribute via the ".data()" API:

var friend = $('button').data('something');
var friendDiv = $('#' + friend);

You can also use class values to relate elements together.

Upvotes: 3

Related Questions