Ways to Display the Chosen Dropdown Value at the Top and Update the Header Text?

When using a dropdown for filters, I want the selected value to be prominently displayed at the top so users can easily see their choice as they continue browsing after closing the dropdown.

For example, if "Option 2" is selected, I would like the text "Category" to be replaced by "Option 2". (I attempted to use HTML select and option tags but they didn't work effectively for triggering the filter.)

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: fixed;
  width: 50px;
  padding: 4px;
  z-index: 1;
}

.dropdown:hover .dropdown-content {
  display: block;
}

p {
  font-size: 16px;
}
<div class="dropdown">
  <span>Category</span>
  <div class="dropdown-content">
    <a href="www.site.com/option1">
      <p>Option 1</p>
    </a>
    <a href="www.site.com/option2">
      <p>Option 2</p>
    </a>
    <a href="www.site.com/option3">
      <p>Option 3</p>
    </a>
  </div>
</div>

Answer №1

When a question is tagged with [jQuery], there is no need to alter the HTML in order to achieve the desired result.

$('a', '.dropdown-content').on('click', function() {
    $(this).closest('.dropdown').find('span').text(this.text());
});

This code snippet will apply the necessary functionality to all dropdowns that are similarly structured on the webpage.

By using DOM traversal from the clicked element to the respective span element, any potential interference between different dropdowns is avoided.

Answer №2

Quite straightforward. To simplify things, I suggest assigning a class to each link and possibly one to the span as well for added organization. In the end, your code will resemble something like this:

<div class="dropdown">
     <span class="selected-category">Category</span>
     <div class="dropdown-content">
          <a class="dropdown-option" href="www.site.com/option1"><p>Option 1</p></a>
          <a class="dropdown-option" href="www.site.com/option2"><p>Option 2</p></a>
          <a class="dropdown-option" href="www.site.com/option3"><p>Option 3</p></a>
     </div>
</div>
document.querySelector('.dropdown-option').forEach(elem => elem.onclick = (event) => document.querySelector('.dropdown .selected-category').innerText = event.currentTarget.innerText);

If adding a class name isn't feasible, simply create a precise selector by using element types instead.

const categorySpan = document.querySelector('.dropdown span');
const dropdownItems = document.querySelector('.dropdown div a');

Subsequently, apply the same logic as with classes.

Edit: Revisions made in response to feedback from Heretic Monkey (much appreciated!)

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 Angular ternary operator can be used in conjunction with functions for optimal

Consider this scenario: I have two functions that are triggered by a button click: <button ng-click="functionOne || functionTwo()"></button> However, I want to optimize this setup so that the functions are only called if they return a value. ...

Struggling to set up a vertical grid using CSS in Bootstrap 3

Currently in the process of working on my final project as a student. Utilizing Bootstrap 3, I am striving to construct a grid that mirrors the structure depicted in the image below: Thus far, I have only achieved success in creating grids that span hori ...

Ways to prevent modal from flickering during event changes

I'm struggling with a current issue and need help identifying the cause and finding a solution. The problem arises from having a nested array of Questions, where I display a Modal onClick to show Sub questions. However, when clicking on the Sub Quest ...

The NodeJS nedb function seems to be ignoring the await keyword

The time it takes for the function checkExists to run is too lengthy. Despite attempting to implement await and async functions, using var exists = await checkExists(data.email); still results in undefined value due to not properly awaiting for checkExists ...

Displaying information in a table with a fixed column width and the

I am attempting to create a table with fixed columns and scrolling functionality similar to the example at this link: Here is the source code for reference: The main issue I am facing is that in the provided sample, the table has fixed widths and heights ...

Get the host name using Node.js server without using the 'req' parameter

Currently, I am utilizing req.headers.host to identify the host name of the server, which works well when dealing with incoming requests at the server. However, I am curious about how one can determine the host name without a request (i.e. without req). T ...

Unable to delete React element by ID as it is undefined

Having some trouble deleting an item by ID with React. Despite the backend routes functioning properly (node and postgresql), every attempt to delete an item results in it reappearing upon page refresh. The command line indicates that the item being delete ...

Adding elements to an array using push method during a loop where elements are

After experimenting with this code on jsfiddle, I am puzzled as to why it doesn't generate an array of 5 objects, each with a different id property: var arr = ["1", "2", "3", "4", "5"]; var clone = {"id": "0", "name":"Matthew"}; var arrObj = []; var ...

Transmitting a row of an HTML table back to Google Sheets

Is there a way to create buttons for each row in a table that, when clicked, send the entire row back to another sheet along with a timestamp? I am currently generating the table from an array but facing issues accessing the elements within it. Both the .g ...

What are the best ways to condense this JavaScript snippet?

Seeking suggestions for enhancing my coding skills. How can this code be optimized for brevity and efficiency? var resultsConstructionYear = readCookie('constructionYear'); switch (resultsConstructionYear) { case 3: document.getEleme ...

How to perfectly center a modal window/div vertically on an iPad

Currently, I am using a simple modal window script that functions well on various browsers, including the iPad. However, I have encountered an issue where the modal window appears at the top of the page on the iPad. This causes it to be out of view if the ...

How can Media Queries help make a search box adapt to different screen sizes?

Currently, this is my code snippet. My goal is to make it drop below my logo on the left side as the screen size decreases. Thank you in advance for any suggestions! @media screen and (max-width:959px){ #wrapper{ width: 100%; ...

Choose the initial search result without actually opening it using jQuery

I am working on an HTML file that contains multiple input fields, which get automatically filled when a corresponding item is selected from the auto-complete feature. Here is a snippet of my HTML code: <table class="table table-bordered"> <u ...

Reload the Angular application and navigate to a different state

Introduction In my extensive angular application, there are numerous forms for various items. These forms are associated with action objects that have unique schemaforms. The dropdowns in these forms vary based on the specific action and its parent comp ...

Tips for attaching my navigation bar to the top of the webpage

Can anyone assist me in fixing the top portion of my webpage so that it stays in place? I attempted to use the position:fixed attribute, but this caused issues as my content started overlapping with the fixed divs. You can find my website here: www.croo ...

Extracting information from nested JSON objects with key/value relationships

Imagine a scenario where you have a JSON array with various key/value pairs in each object. While you already know how to target a specific key/value using JavaScript, what if you need to search through the entire JSON data to locate an item and also find ...

midway through processing HTML form

In the past, I have come across web forms that span multiple pages. If invalid information is entered on any page, it triggers an error message and requires the user to rectify their input. Despite this, I am having trouble locating resources to guide me ...

Swap out the entire page with the contents from a dynamically loaded AJAX page

In my current project using JQuery, I am trying to implement a feature that replaces the entire page with the contents of an ajax load. While there are answers available on how to do this from the loading page itself, I am interested in achieving this dire ...

Is it possible to eliminate the css class prefix when using Modular css in React?

When working with React & NextJS, I have observed that my modular SCSS files are automatically prefixing my classnames with the name of the file. Is there a way to turn off this feature as it is making the DOM structure difficult to interpret? For instanc ...

The charset is failing to function properly when using the French language

Encountering an issue with the French language on a website I'm currently developing ... Specifically, there are menu bars, tabs, and text within each tab involved. Upon setting charset=ISO-8859-1, the body text functions correctly, but the menu bar ...