Matt Smith
Matt Smith

Reputation: 2120

jQuery show/hide based on select dropdown not working as expected

I'm attempting to show/hide <div>'s based on values chosen from a select drop-down menu.

HTML

<select id="selReport">
  <option value="Report One">Report One</option>
  <option value="Report Two">Report Two</option>
  <option value="Report Three">Report Three</option>
  <option value="Report Four">Report Four</option>
</select

<div id="Report One" class="description">
  <p>...</p>
</div>
<div id="Report Two" class="description">
  <p>...</p>
</div>

I'm using the following jQuery snippet to hide the <div>'s and then show them based on what is selected in the drop-down menu:

jQuery

$('.description').hide();
$('#selReport').change(function () {
  $('description').hide()
  $("[id='" + this.value + "'").show();
});    

When a new option is selected from the drop-down menu the previous <div> that was displayed doesn't hide. It stays displayed and I don't know why. Can someone offer a suggestion?

Upvotes: 0

Views: 730

Answers (2)

taxicala
taxicala

Reputation: 21759

First change your ids to dont have any spaces (space is an invalid character for IDs) like follows:

<div id="Report-One" class="description">
  <p>...</p>
</div>
<div id="Report-Two" class="description">
  <p>...</p>
</div>

And second (little typo here :)) change:

$('description').hide();

to:

$('.description').hide();

Upvotes: 3

Claudio Redi
Claudio Redi

Reputation: 68400

You have to change

$('description').hide() // tag selector

by

$('.description').hide() // class selector

Your code as it is, selects elements with tag description what is not what you're looking for

EDIT

Missed the Id thing (credit to @taxicala). Definitively you need to change your ids.

<select id="selReport">
  <option value="ReportOne">Report One</option>
  <option value="ReportTwo">Report Two</option>
  <option value="ReportThree">Report Three</option>
  <option value="ReportFour">Report Four</option>
</select

<div id="ReportOne" class="description">
  <p>...</p>
</div>
<div id="ReportTwo" class="description">
  <p>...</p>
</div>

Upvotes: 0

Related Questions