Home > front end >  How Do I Get the Selected Value from a Dropdown to Appear at the Top and Replace the Header?
How Do I Get the Selected Value from a Dropdown to Appear at the Top and Replace the Header?

Time:12-29

I am using a dropdown for filters and want the selected value from the dropdown to appear at the top so users can see what their selection is when the dropdown closes and they continue browsing.

In this scenario, let's say I select "Option 2", I would want the span section value of "Category" to be replaced by "Option 2". ( I tried using the HTML select and option tags but they just don't work to trigger the filter.)

HTML

<div >
     <span>Category</span>
     <div >
          <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>

CSS

.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;
  }
}

CodePudding user response:

Pretty simple stuff. To make it easier, I would add a class to each of the links and probably one to the span too for good measure. All in all, you would have something that looks like this:

<div >
     <span >Category</span>
     <div >
          <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>
const items = document.getElementsByClassName('dropdown-option');

[].slice.call(items).forEach(el => el.onclick = (e) => document.body.querySelector('.dropdown .selected-category').innerText = e.currentTarget.innerText);

if you can't add a class name, you just need to build a good selector using the element types instead.

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

then its the same thing as with the class.

CodePudding user response:

Question is taggged [jQuery], therefore, without needing to change the HTML ...

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

This expression will give all similarly constructed dropdowns on the page the required behaviour.

By traversing the DOM from the clicked element to the span element, there's no fear of cross-talk between different dropdowns.

  • Related