Use Jquery to revert the chosen element back to its original base state

I have implemented a select box where selecting a value in the main select box "Domains" will reveal another select box called "Types" such as Diatoms or Flagellates. I have successfully achieved this functionality, but now I am facing an issue with resetting the selected item in the newly appeared select box back to the default option of the main select box. For example, if I select "Diatoms" in the Domains select box and then choose an item within Diatoms category, and then switch to other items in Domains causing a different select box to appear, the previously selected Diatoms item remains selected. I want to revert it back to the default first option instead. Here is my code:

I have attempted using 'selectedIndex', 0 to reset the selected item, but it did not work.

HTML

<ul class="inline_list">
    <li class="Domains">
        <select>
            <option selected disabled hidden>Domains</option>
            <option value="Diatoms">Diatoms</option>
            <option value="Flagellates">Flagellates</option>
            <option value="Dinoflagellates">Dinoflagellates</option>
            <option value="Ciliates">Ciliates</option>
            <option value="Coccolithophore">Coccolithophore</option>
            <option value="Miscellaneous">Miscellaneous</option>
            <option value="Other_plankton">Others</option>
        </select>
    </li>
    <li class="Diatoms domains_types">
        <select>
            <option selected disabled hidden>Types</option>
            <option value="Asterionellopsis">Asterionellopsis</option>
            <option value="Bacillaria">Bacillaria</option>
        </select>
    </li>
    <li class="Flagellates domains_types">
        <select>
            <option selected disabled hidden>Types</option>
            <option value="amoeba">amoeba</option>
            <option value="Chrysochromulina">Chrysochromulina</option>
        </select>
    </li>
    <script src="js/select_box.js"></script>
</ul>

CSS

.domains_types{
            display: none;
        }

Jquery

$(document).ready(function(){
    $('.Domains').ready(function(){
        $('select').change(function(){
            $("select option:selected").each(function(){
                if($(this).attr("value")=="Diatoms"){
                    $('.domains_types').hide();
                    $('.Diatoms').css('display','inline-block');
                }
                if($(this).attr("value")=="Flagellates"){
                    $('.domains_types').hide();
                    $('.Flagellates').css('display','inline-block');
                }
            });
        }).change();
    });
});

Answer №1

Your code has room for optimization to eliminate redundancy. Here are some simple enhancements that can be implemented:

  • Eliminate the ready event listener from $('.Domains'). The ready function is specifically intended for the document object and corresponds to the DOMContentLoaded event. It is essentially a shortcut method provided by jQuery.
  • Rather than iterating through all options, you can directly retrieve the value of the <select> element by using this.value. This streamlines your code by reducing one layer of nesting.
  • Rather than crafting individual if statements for each value, utilize '.' + this.value to select the appropriate element. This works due to a direct mapping between the first set of <select> element's values and the corresponding <li> wrappers for the subsequent level of <select> elements. For example, if 'Flagellates' is selected, then the selector will target $('.' + this.value), which translates to $('.Flagellates').
  • To reset the second-level <select> element, simply pick the first option and mark its selected property as true, like so:
    $('option:first-child').prop('selected, true')
    .
  • hidden is not a relevant attribute/property for an <option> element and can be removed.

Following these improvements, here is the refined and operational code snippet:

$(document).ready(function() {
  $('.Domains select').change(function() {
    $('.domains_types')
      .hide()
      .find('select option:first-child')
      .prop('selected', true);
      
    $('.' + this.value).css('display', 'inline-block');
  }).change();
});
.domains_types {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="inline_list">
  <li class="Domains">
    <select>
      <option selected disabled>Domains</option>
      <option value="Diatoms">Diatoms</option>
      <option value="Flagellates">Flagellates</option>
      <option value="Dinoflagellates">Dinoflagellates</option>
      <option value="Ciliates">Ciliates</option>
      <option value="Coccolithophore">Coccolithophore</option>
      <option value="Miscellaneous">Miscellaneous</option>
      <option value="Other_plankton">Others</option>
    </select>
  </li>
  <li class="Diatoms domains_types">
    <select>
      <option selected disabled>Types</option>
      <option value="Asterionellopsis">Asterionellopsis</option>
      <option value="Bacillaria">Bacillaria</option>
    </select>
  </li>
  <li class="Flagellates domains_types">
    <select>
      <option selected disabled>Types</option>
      <option value="amoeba">amoeba</option>
      <option value="Chrysochromulina">Chrysochromulina</option>
    </select>
  </li>
</ul>

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

The process of loading and saving extensive data to the local storage of a user's Firefox browser involves extensive reading and writing operations

Our team has developed a sophisticated HTML5 offline application that houses a substantial amount of data, totaling tens of megabytes. We are looking for a way to allow users to save and retrieve copies of this data on their disk. While we have made some ...

What's the best way to fix a div to the bottom left corner of the screen?

I have explored various solutions regarding this issue, but none of them seem to meet my specific requirements. What I am trying to achieve is the correct positioning of a div as depicted in the green area in the image. https://i.sstatic.net/O9OMi.png Th ...

What is the best way to integrate Socket.IO into an Electron application?

I've been looking to incorporate Socket.IO into my Electron application, but the lack of documentation and examples has made it quite challenging. I would greatly appreciate if someone could provide insights on how multiple clients can communicate thr ...

In my attempts to retrieve specific statistics from the PokeAPI using Axios and Node.js, I encountered an error

Having an issue while trying to utilize the Pokemon API. Whenever attempting to access the attack, HP and speed stats, all Pokemons show up as undefined! Can someone please point out what might be wrong with my API call? const axios = require('axios&a ...

Building an Angular 4 universal application using @angular/cli and integrating third-party libraries/components for compilation

While attempting to incorporate server side rendering using angular universal, I referenced a post on implementing an angular-4-universal-app-with-angular-cli and also looked at the cli-universal-demo project. However, I ran into the following issue: Upon ...

Converting JavaScript code to jQuery and integrating it into a WordPress website has become a common practice

I recently developed a working javascript function as shown below: function calc(A,B,SUM) { var one = Number(A); var two = Number(document.getElementById(B).value); if (isNaN(one)) { alert('Invalid entry: '+A); one=0; } if (isNaN(tw ...

Node JS login leads to fetching /favicon.ico

I've implemented a login/register system using express (passport) on my website. I'm facing an issue where after the user logs in, they are redirected to /favicon.ico instead of the saved originalUrl. Can anyone help me identify what might be cau ...

Automatic Textbox Closer

Connected to this AngularJS issue on IE10+ where textarea with placeholder causes "Invalid argument." and also this AngularJS 1.1.5 problem in Internet Explorer with ng-show and objects (Bug), we had to resort to using the textarea element as a self-closin ...

``Next.js allows you to nest components within a component to create routing functionalities

My login page has 3 different roles for logging in: Admin, Student, and Company. Instead of redesigning the entire page, I just want to update the login component for each specific role. Login Page export default function Authpage(){ return( ...

Are cookies always included in client requests?

With every interaction between the server and browser, cookies are exchanged back and forth. However, what happens when an image is requested? <img src='myPic.jpg' /> Is the browser also sending cookies during this type of request? If i ...

How to implement hover effect to show child div within parent div using React.js

Hey there! I'm fairly new to working with react js and currently trying to add some animation to a nested div. The parent div, known as " portfolio-product-item ", showcases a featured image pulled from the WP REST API. Inside this parent div, there&a ...

Tips for transmitting one or multiple data using jquery.ajax

I found this code on stackoverflow and it is working well for uploading multiple files. However, I am facing an issue where I cannot send additional parameters along with the file upload. Despite trying various methods, I have been unsuccessful in sending ...

Issue with value not updating following second ajax request

My project involves making an ajax call to render out a shopping cart using jQuery. function showShoppingCart() { $.ajax({ url: 'functions/show-cart.php', type: 'POST', dataType: 'json', }) ...

Sleek and versatile sidebar reaching full height

Is there a way to make my sidebar cover the full height of the screen without using position: fixed? The code I've tried doesn't seem quite right. Any tips? JSFindle: http://jsfiddle.net/Pw4FN/57/ if($(window).height() > $('#page-contai ...

What are the steps to testing an endpoint with Jasmine/Karma?

Within one of my components, there is a method that makes a call to an endpoint in the following manner... private async getRolesAsync(): Promise<void> { const roles = await this.http.get<any>('https://sample-endpoint.com').toProm ...

Why is my data not being saved to the database when using eloquent?

I am encountering an issue with my form submission. Although the data is present when using dd() on Requests, the save() function does not work as expected, resulting in the data not being stored in the table. I am attempting to add new Users via a backoff ...

Using CSS backdrop-filter to create a unique blurred border effect for your web elements

In my quest for achieving unique visual effects, I have been experimenting with the backdrop-filter and element borders. While it is easy to create an element that blurs its background, I am facing challenges in making the filter affect only the border are ...

Transitioning a user interface from Excel to ASP.NET

Currently, we have an Excel spreadsheet that is utilized for data collection from users and to populate our database. Now, the need arises to develop an asp.net page to gather this data instead. We are facing some challenges in determining the most effect ...

What are the steps for publishing a Three.js project on github pages?

Currently, I've been putting together my own personal portfolio website which involves using the Three.js library. The library has been downloaded onto my laptop and when running locally, everything works smoothly. Now, I want to move forward by deplo ...

How can I incorporate a custom color into a preset navbar on an HTML webpage?

<div class="navbar-header"> <button aria-controls="navbar" aria-expanded="false" data-target="#navbar" data-toggle="collapse" style="color: blue;" class="navbar-toggle collapsed" type="button"> <i class="fa fa-reo ...