Skip to content
Advertisement

Remember select(by Cookie) option from autocreated JS array(depending from user`s choice)

How to save user`s choice in city selection(city_id) by Cookie? Cities are autocreated after update page. HTML

 <select name="country_id" id="country_id" class="select_class">
    <option value="USA">USA</option>
    <option value="Russia">Russia</option>
 </select>
 <select name="city_id" id="city_id">

JS

 var countries = {
    USA: ['NewYork', 'Chicago', 'Las Vegas'],
    Russia: ['Moscow','Saint-Petersburg','Vladivostok']
};

var city_update = function() {
    var country_id = $('#country_id option:selected').val();
    var emptycity = $('#city_id').empty();
    for (i in countries[country_id]) {
        var country_name = countries[country_id][i];
        emptycity.append($('<option>').val(country_name).text(country_name));
    }
};
$('#country_id').change(city_update);
city_update();

Advertisement

Answer

You can either store it as a cookie or use localStorage, depending on what browsers you support. By the looks of your code, you’re just adding the country as an option to the city_id field?

localStorage is much simpler (not all browsers support it), you would just need to bind an event to city_id change:

$('#city_id').change(function() {

localStorage.setItem('selected-city',$(this).val());

});

Also, you’re better off doing for(var i = 0;i < countries[country_id].length;i++) {... instead of for in for performance reasons, and because you’re looping through an array, rather than an object (objects need a for in loop).

Alternatively, you can use the below function to set it using a Cookie e.g.:

var cookie = new Cookie();
    $('#city_id').change(function() {

    cookie.set('selected-city',$(this).val(), 86400);
    // access with cookie.get('selected-city');
    });

function Cookie() {
    this.get = function(name) {
        var cookies = document.cookie.split(";");
        for(var i = 0; i < cookies.length; i++) {
                var a = cookies[i].split("=");
                if(a.length == 2) {
                    a[0] = a[0].replace(/^s+|s+$/g, '');
                    a[1] = a[1].replace(/^s+|s+$/g, '');
                    if(a[0] == name) {
                        return unescape(a[1]);
                    }
                }
        }
        return "";
    };
    this.set = function(name, value, seconds, path, domain, secure) {
        var cookie = (name + "=" + escape(value));
        if(seconds) {
            var date = new Date(new Date().getTime() + (seconds * 1000));
            cookie += ("; expires=" + date.toGMTString());
        }
        cookie += (path ? "; path=" + path : "");
        cookie += (domain ? "; domain=" + domain : "");
        cookie += (secure ? "; secure" : "");
        document.cookie = cookie;
    };
    this.del = function(name, path, domain, secure) {
        var cookie;
        switch(typeof name) {
            case 'object':
                for(var i = 0; i < name.length; i++) {
                    cookie = name[i] + "=; expires=Thu, 01-Jan-70 00:00:01 GMT";
                    cookie += (path ? "; path=" + path : "");
                    cookie += (domain ? "; domain=" + domain : "");
                    cookie += (secure ? "; secure" : "");
                    document.cookie = cookie;
                }

                break;
            default:
                cookie = name + "=; expires=Thu, 01-Jan-70 00:00:01 GMT";
                cookie += (path ? "; path=" + path : "");
                cookie += (domain ? "; domain=" + domain : "");
                cookie += (secure ? "; secure" : "");
                document.cookie = cookie;
                break;

        }


    };
}

Finally, update this:

var city_update = function() {
    var country_id = $('#country_id option:selected').val();
    var emptycity = $('#city_id').empty();
    for (i in countries[country_id]) {
        var country_name = countries[country_id][i];
        var selected = country_name == cookie.get('selected-city') ? true : false;
        emptycity.append($('<option>').attr('selected',selected).val(country_name).text(country_name);
    }
};
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement