"Exploring the mystery of why a div element is not toggling show/hide based

I want to implement a feature where a specific div is hidden based on the option selected from a drop-down menu.
Here's how it should work:
When the document loads, no div will be visible
Selecting option 1 will display OneLevel
Selecting option 2 will show TwoLevel
Selecting option 3 will reveal ThreeLevel

<!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$("#Level").hide();
function WorkflowLevel(obj) {
    var selectBox = obj;
    var selected = selectBox.options[selectBox.selectedIndex].value;

     $("#Level").hide();

    switch (selected) {
    case '0':
        $("#Level").hide();
        break;
    case '1':
        $("#Level").hide();
        $("#Level#OneLevel").show();
        break;
    case '2':
        $("#Level").hide();
        $("#Level#TwoLevel").show();
        break;
    case '3':
        $("#Level").hide();
        $("#Level#ThreeLevel").show();
        break;
    }

}
</script>
</head>
<body>

<select id="WorkflowLevel" class="form-control" name="show_text_area" onchange="WorkflowLevel(this)">
    <option value="0">Select</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

<div id="Level OneLevel">1</div>
<div id="Level TwoLevel">2</div>
<div id="Level ThreeLevel">3</div>

</body>
</html>

Answer №1

Forget about using a switch case. Opt for utilizing index position to toggle visibility effectively.

$(".Level").hide();

function WorkflowLevel(obj) {
  var selected = $("option:selected", obj).index();
  $(".Level").hide();
  selected && $(".Level:eq(" + (selected - 1) + ")").show();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="WorkflowLevel" class="form-control" name="show_text_area" onchange="WorkflowLevel(this)">
  <option value="0">Select</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

<div class="Level OneLevel">1</div>
<div class="Level TwoLevel">2</div>
<div class="Level ThreeLevel">3</div>

Answer №2

It appears that having multiple ID's for one element is not possible. One alternative is to use a class like "level" and assign an ID based on number, such as id="OneLevel" or just id="One". This way, in your hide/show selector, you can use something like $(".level#One").hide();

If you want more information about using multiple IDs, you can visit this link: Can an html element have multiple ids?

Answer №3

Check out this example on how to make rewriting a lot less painful. This code utilizes a custom attribute named showId to display the correct box based on the value selected from .val() of our WorkFlowLevel selection. This method simplifies the process of adding more items in the future.

$("#WorkflowLevel").change(function () {
  $(".Level").hide()
  $("[showId="+$(this).val()+"]").show();
}).trigger("change");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="WorkflowLevel" class="form-control" name="show_text_area">
    <option value="0">Select</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

<div class="Level" showId="1">1</div>
<div class="Level" showId="2">2</div>
<div class="Level" showId="3">3</div>

Answer №4

To ensure uniqueness, do not assign the same id to multiple divs. Instead, utilize class. Here is an example:

$(document).ready(function(){
$(".lvl").hide();
  $("#WorkflowLevel").on('change', function(){
    $(".lvl").hide();
    $("#Level"+$(this).val()).show();
  })
  
})
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<select id="WorkflowLevel" class="form-control" name="show_text_area" >
    <option value="0">Select</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

<div id="Level1" class="lvl">1</div>
<div id="Level2" class="lvl">2</div>
<div id="Level3" class="lvl">3</div>

Answer №5

$(".Level").hide();

$(".WorkflowLevelSelect").change(function() {
  $(".Level").hide();

  var selectedValue = $("option:selected", this).val()

  $(".Level").filter(function() {

    return $(this).attr("data-id") == selectedValue;
  }).show()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="WorkflowLevel" class="form-control WorkflowLevelSelect" name="show_text_area">
    <option value="0">Select</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

<div class="Level OneLevel" data-id="1">1</div>
<div class="Level TwoLevel" data-id="2">2</div>
<div class="Level ThreeLevel" data-id="3">3</div>

  1. Add data-attribute that corresponds to the value of options
  2. Change ID to Class of div Level ID should be unique
  3. Use filter to select the div that has data attribute equal to option selected value

Answer №6

There are a few issues found in both the html and js code. It can be confusing when you use the same id like id="Level OneLevel" . Each id should be unique.

Instead, utilize Level as a general class to hide all the div elements. Avoid using #Level#TwoLevel and similar patterns as they do not correspond to any DOM element with that id.

JS

    $(".Level").hide();
    
    function WorkflowLevel(obj) {
      var selectBox = obj;
      var selected = selectBox.options[selectBox.selectedIndex].value;
    
      $(".Level").hide();
    
      switch (selected) {
        case '0':
          $(".Level").hide();
      

    break;
    case '1':
      $(".Level").hide();
      $("#OneLevel").show();
      break;
    case '2':
      $(".Level").hide();
      $("#TwoLevel").show();
      break;
    case '3':
      $(".Level").hide();
      $("#ThreeLevel").show();
      break;
  }

}

HTML

<div id="OneLevel" class="Level">1</div>
<div id="TwoLevel"  class="Level">2</div>
<div id="ThreeLevel"  class="Level">3</div>

DEMO

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to invoke a function within an AngularJS controller?

Currently, I am exploring the most efficient method of calling a function from an AngularJS controller externally. In our setup, data is transmitted from a Python backend to the frontend using JavaScript functions. To feed this data into the Angular contr ...

What other aspects of mobile design could mobile-specific CSS be focused on aside from screen size?

As a newcomer to responsive web development, I have found myself puzzled by media queries. For example, how does the following code snippet target specifically iPhones with a max-device-width of 320px: @media screen and (max-device-width: 320px) {} Woul ...

Real-time calculation of dropdown options

Check out the demonstration here: http://jsfiddle.net/NaUAL/61/ <select name="one" id="one" > <option value="0" >Choose an option *</option> <option value="3000" >Plan A</option> <option ...

Utilizing JavaScript to Parse Datasnap Output

I am currently working on a project in Delphi where I need to display a list of data in a listbox. However, I am struggling to understand how everything comes together. Luckily, I found a helpful answer that provided me with a solution using a dataset def ...

Determine distinct items in an array that match a predefined criteria

I have a list of objects with two keys, img1 and img2. I need to identify unique objects based on the values of img1, while also retaining the corresponding value of img2. This is the current code I am using: const imgs_arr = [ ...new Set( inpu ...

ng-repeat and $scope problem

I am having an issue with my page where I display 3 images in a row using Ng-repeat. When I click on any image, it only shows the first image that was displayed in that particular row. Template: <div id="galscrolldiv" class="row" ng-repeat="image in i ...

Unable to send JSON data from server to client following a successful file upload operation

I'm currently working on a project that involves NodeJS, Express, JQuery, and Typescript. The issue I'm facing is related to uploading a file from the front end, which is successful. However, I'm encountering difficulties in returning a JSON ...

Tips for customizing a button created dynamically using JavaScript

I have been attempting to insert a button using .js into my HTML code. The purpose of this button is to appear every time I click on another button (identified with the id "imageChoose") which displays a preview of an image. This new button, labeled as rem ...

Creating a constant in an AngularJS module: The definitive guide to defining module-specific constants

Within a page, numerous Angular modules are present. I have set up a constant for each module containing the version number. var module1 = angular.module('module1').constant('version', '1.2.3'); var module2 = angular.module(& ...

Using self-hosted fonts in Next.js does not function properly

Exploring Font Hosting in Next.js I am currently investigating the use of self-hosted fonts within a Next.js application. Previous Attempts https://i.sstatic.net/AuIwB.png https://i.sstatic.net/P6ekH.png Outcome So far, CSS only seems to recognize th ...

Divs animated with jQuery keep on moving even after the animation has finished

My current project involves animating a single circle that scales, collides with two nearby circles, and then causes those circles to animate to specific positions. While everything works as expected, there is an issue where the two circles involved in the ...

Receiving HTML codes through AJAX requests using .htaccess

retrieving html codes after ajax post request on the client side: $('#bgn').live('click',function(){ var data = {action:'today'}; $.post('inc/ajax-handler.php',data,function(response){ $('#result&a ...

Selenium navigating an unordered list without returning the expected text

I'm currently in the process of developing a search bot for Craigslist using Selenium. I've managed to successfully iterate through the unordered list of search results, but unfortunately, I'm not able to extract the specific link text that ...

New action triggered by a click event following the prevention of the default behavior

Currently, the mobile menu on my test site (800px wide or less) does not have drop-down folder functionality. I am looking to make the mobile navigation menu function in the same way as it does on desktop. Check out my website here By default, when click ...

What is the purpose of the Google variable if it has not been declared before?

While experimenting with the Google Maps API for Javascript, I stumbled upon the Hello World section. <script> var map; function initMap() { map = new google.maps.Map(document.getElementById('map'), { center: {lat: -34.397, l ...

After submitting the form, the delete button in Bootstrap 4 has transformed into an unusual shape

I have a panel on my page, inside the panel header there is a red delete button. The panel content includes a form with several buttons (the red delete button is not inside the form, but linked to it with the form="abc" attribute). In the image below, whe ...

Tips for rearranging several input containers at once

I'm struggling to align the two cells for the address input. I can adjust the inline one easily, but the others are giving me trouble. I'm looking for some creative feedback on how to make this work. .EMBody { position: relative; backgrou ...

Leveraging window.location.origin with modernizr

My goal is to achieve the following: var siteBaseUrl = window.location.origin; However, in IE 9 it returns undefined I am attempting to grasp how I can utilize modernizr based on the advice provided here: $window.location.origin gives wrong value when u ...

What is the best method to extract information from JavaScript tables using Python and Selenium?

As a beginner in Python, JavaScript, and Web-Scraping, I am facing the challenge of extracting data from tables on a specific webpage (https://www.mcmaster.com/cam-lock-fittings/material~aluminum/) and saving it into a csv file. https://i.sstatic.net/xQBO ...

Is there a way to refresh a Material-UI data table in React whenever a user takes any action?

I am facing an issue with my Lock-Unlock button and delete button. The problem arises when I render data from axios using the useEffect hook, it works fine. However, if I try to lock or unlock a user, the table does not update automatically. This indicates ...