User014019
User014019

Reputation: 1247

How to retain a value of dropdown using JS?

I have a three dropdown with 1 submit button. Now, I'm trying to retain the value of each dropdown after the user clicked the input submit. But the Jquery I have is not working. I use PHP to displayed the output of the dropdown when the user clicked it.

Note: The page is refresh when the user clicked the input submit.

How to fix this? See in plunker

JS:

$(document).ready(function(){
    $('#dropdown').change(function(){
        var option = $(this).find('option:selected').val();
        $('#dropdown').val(option);
    });

});

Upvotes: 1

Views: 4589

Answers (4)

Alexandre
Alexandre

Reputation: 121

Although I assume OP's question asks for a JS solution, I do want to bring something else to the table because I was also searching to solve the same problem. However, I ended up solving it in a manner that I considered to be satisfying.

In my case I'm using Flask as the backend, but I believe the solution should be at least similar for other use cases.

On the HTML where the dropdown is located, I pass a variable from the backend which is originally set to be some default value of my choice. Let's call this variable default_var_set_in_backend. This will ultimately be fed to the HTML and will look like as follows:

<select name="some_name_you_want" onchange="this.form.submit()">
    <option selected="selected">{{ default_var_set_in_backend }}</option>

Once a change is made in the dropdown value by the user (in my case it's a GET request), I update the variable default_var_set_in_backend to be equal to this new choice. Now, the HTML will reflect the latest choice made by the user once the page refreshes.

Upvotes: 0

Nikhil Nanjappa
Nikhil Nanjappa

Reputation: 6632

You can get the values easily by making use of the model attribute present in the select element.

First add a onclick function like so

<input type="submit" name="submit" value="Submit" onclick="getValues()"/>

Then get the value on submit of the button(Entire code) Plunkr

I had a look at your code, the way your selectbox rendering is setup we have to explicitly call the updateSelect() function for the options to work well. This function makes your selectbox "dynamic".

var first = localStorage.getItem("firstDropDown");
var second = localStorage.getItem("secondDropDown");
var third = localStorage.getItem("thirdDropDown");

if(first !== null && second !== null && third !== null) {
  setValues(); //this should come after getting  the values above
}

function getValues() {
  var first = document.getElementsByTagName("SELECT")[0].getAttribute("model");
  var second = document.getElementsByTagName("SELECT")[1].getAttribute("model");
  var third = document.getElementsByTagName("SELECT")[2].getAttribute("model");

  localStorage.setItem("firstDropDown", first);
  localStorage.setItem("secondDropDown", second);
  localStorage.setItem("thirdDropDown", third);
}

//on load when this function is called globally, the values from the localStorage will be set to the dropdown values.
function setValues() {
  //for first dropdown
  document.getElementsByTagName("SELECT")[0].setAttribute("model", first); 
  document.getElementsByTagName("SELECT")[0].value = first;
  updateSelect(document.getElementsByTagName("SELECT")[0]);
  //for second dropdown
  document.getElementsByTagName("SELECT")[1].setAttribute("model", second);
  document.getElementsByTagName("SELECT")[1].value = second;
  updateSelect(document.getElementsByTagName("SELECT")[1]);
  //for third dropdown
  document.getElementsByTagName("SELECT")[2].setAttribute("model", third);
  document.getElementsByTagName("SELECT")[2].value = third;
  updateSelect(document.getElementsByTagName("SELECT")[1]);
}

To retain the value you have no choice but to use a window.localStorage like so -

localStorage.setItem("firstDropDown", first);
localStorage.setItem("secondDropDown", second);
localStorage.setItem("thirdDropDown", third);

Then fetch the value

var first = localStorage.getItem("firstDropDown");
var second = localStorage.getItem("secondDropDown");
var third = localStorage.getItem("thirdDropDown");

Upvotes: 1

KOUSIK MANDAL
KOUSIK MANDAL

Reputation: 2052

Use local storage with all option;

$("#dropdown").change(function(){

      var html=$("#dropdown").html();
      localStorage.setItem("myapp-selectval",html);

      localStorage.setItem("myapp-selectvalselected",$("#dropdown").val());              //to retain selected value
})

Now on document load;

window.onload=function()
{
    if(localStorage.getItem("myapp-selectval")!="" && localStorage.getItem("myapp-selectval")!=undefined)
    {
        $("#dropdown").html(localStorage.getItem("myapp-selectval"));

        $("#dropdown").val(localStorage.getItem("myapp-selectvalselected"));                 //to get previously selected value
    }
}

Once again as I said in comment it's not a good solution.

Upvotes: 2

fmt
fmt

Reputation: 993

If the user is going to refresh the page, your best bet is to have the server send down the value that the user just submitted with the new page load.

If that's impossible for some reason, you can use localStorage:

$(document).ready(function(){
    var prevVal = localStorage.getItem('selectValue');
    prevVal && $('#dropdown').val(prevVal);

    $('#dropdown').change(function(){
        var option = $(this).val();
        localStorage.setItem('selectValue', option);
    });

});

Keep in mind that not all browsers support this API yet.

EDIT: If you don't need the browser to refresh, you can use Ajax:

// ...
$('#myForm').submit(function (event) {
    event.preventDefault();
    var option = $('#dropdown').val();
    var fd = new FormData();
    fd.append('dropdown', option);
    $.ajax('/path/to/form/target/', {
        method: 'POST',
        formData: fd
    });
    // ...
});
//...

Upvotes: 1

Related Questions