1

Based on the information here: change dropdown button text on dropdown items selection I am wondering if this code can be modified to take into account a page reload.

I am attempting to get the text from the dropdown link clicked on to stay in the dropdown button on refresh.

$(".btn-toggle").on("click", function() {
  $('.dropdown-menu').toggleClass('open');
});
$(".dropdown-menu li").on("click", function() {
  $('.btn-toggle').text($(this).text());
  $('.dropdown-menu').removeClass('open');
});

This works well as long as there is no page reload.

X Daast
  • 33
  • 4
  • in that case, you can check the selected menu option and based on that show the text of active menu – Ashish Aug 15 '23 at 17:18

3 Answers3

1

You want the selected item of the dropdown to be remembered after refreshing? In that case you need some kind of storage.

You can try the browser's localStorage for example.

localStorage.setItem('storedInitialValue', 'value!') // write
localStorage.getItem('storedInitialValue')  // read

This will be cached in your browser, even if you close and come back.

  • Thanks, Thomas. So if .btn-toggle was the initial value and .dropdown-menu li is the value to write should I use: localStorage.setItem('.btn-toggle', '.dropdown-menu li') localStorage.getItem('.btn-toggle') – X Daast Aug 15 '23 at 17:50
1

On refresh, all variables restart, so you need to save the informacion about selected product to some kind of storage. There are a few options, I'm gonna show you my favorite, and this is Local storage (more about it here)

So, do code will look like this:

$(".btn-toggle").text(
localStorage.getItem("selected") // get item from local storage
? localStorage.getItem("selected")
: "default" //YOUR DEFALUT BUTTON TEXT GOES HERE
);
$(".btn-toggle").on("click", function () {
$(".dropdown-menu").toggleClass("open");
});
$(".dropdown-menu li").on("click", function () {
$(".btn-toggle").text($(this).text());
localStorage.setItem("selected", $(this).text()); // save text to local 
storage
$(".dropdown-menu").removeClass("open");
});
RedApple
  • 119
  • 3
0

Like Thomas said, you need to store the value you want to display on the button somewhere in your application, you could simply store it on your database and pull the value from there. Or you could use the browser's local storage, whatever suits your needs best.