Mohit Gaur
Mohit Gaur

Reputation: 17

How to Retain drop down selected value whose values are coming from ajax response?

I am populating a city drop down on the basis of state drop down selected value through ajax call. i.e. when user clicks any state from state drop down then on the basis of state id, i am making a ajax call which fetches cities name from database on the basis of state id and populates the city drop down. I want to retain the selected text by user in state and city drop downs even when the page gets reloaded. My problem is: when page is reloaded then i display the selected state in state drop down using post array but city drop down again resets to select city option because its values are coming from ajax response for which ajax call is made when user selects any state. Can anyone help me in this regard? Thanks in advance.

Upvotes: 1

Views: 843

Answers (1)

DontVoteMeDown
DontVoteMeDown

Reputation: 21465

You can store the last selected city id in the localStorage/sessionStorage which stores the id in the user's browser when user changes the dropdown value(change event), e.g.:

// to save
localStorage.setItem("city_id", city_id);

// to load
var lastCityId = localStorage.getItem("city_id");

You'll have to implement the selection after your request is completed in your javascript. This is the far I can get with the - few - information you provided in your post. Any new info would be helpful.

Upvotes: 0

Related Questions