skip to Main Content

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.

3

Answers


  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.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. 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");
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search