0

Hi I'm working on a MVC application that has a drop down menu in it, and the items in this drop down are fetched from the DB via a foreach.

foreach (Category item in Model.CategoriesV){    
<input type="submit" class="dropdown-item" id="Show" 
value="@item.CategoriesName" name="CategName" />
 }

I get 3 results from this for each (Mobiles-Consoles-Tablets), I have another div that contains an image gallery. I used this code to hide this gallery once I click on an item in the drop down menu. Here's the image galley(I put it in a Partial View)

<div id="ImageGalleryDiv">
@Html.Partial("_ImageGallery", Model)
</div>

And here's the script that I used to hide the gallery once I click on drop down items list.

 <script>
 $(document).ready(function () {
 $('#Show').click(function () {
 $('#ImageGalleryDiv').hide("100");
 });
 });

Everything is working fine when I click on Mobiles (the first item in the drop down),the others items aren't working. Any help would be appreciated.

Alaa Hershey
  • 85
  • 1
  • 9

1 Answers1

2

id should be unique. That is it's purpose. Uniquely identifying an element. You are not allowed to use duplicate id's on a page. It can result in unwanted behavior like you are experiencing now. Basically, jQuery gets the first element that it finds with the id and then ignores all the other. Also in plain javaScript we not not have a getElementsById method but getElementById.

Read more about it here -> Why are duplicate ids not allowed in HTML

So you can use a class instead.

Also, class and id should be lowercase and dash separated string-string ( if the consist of multiple words ) , not camelCase.

See example below

const categories = ['Mobiles', 'Consoles', 'Tablets']


categories.forEach(categ => {
  const input = `<input type="submit" class="dropdown-item show" id="show-${categ}" value=${categ} name=${categ} />`
  $('#categories').append(input);
});

$('.show').click(function() {
  $('#image-gallery-div').hide("100");
});
#image-gallery-div {
  height: 100px;
  background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="categories">

</div>
<div id="image-gallery-div">

</div>
Mihai T
  • 17,254
  • 2
  • 23
  • 32