2

I have 10 separate home pages for different languages. Language can be selected from index.html page.

Problem is that only home page is multilingual in website. All other pages are in English language. When i am navigating from other pages to home page how can i store value of language which i had selected on home page earlier?

I am defining language by HTML "lang" attribute in tag of each home page. The code i am using as below:

$(document).ready(function(){
   var theLanguage = $('html').attr('lang');    

   $(".homeBtn a").click(function(){
       alert(theLanguage)
       var newHref = "home_"+theLanguage+".html";
       $(".homeBtn a").attr("href", newHref)

   });
});

I am getting undefined value of "theLanguage" variable in alert. I think variable is not passing from home page to other pages.

Please help me to resolve this.

vijay
  • 63
  • 1
  • 7
  • sounds like you need to send the lang variable value to the backend and disperse it to the pages there. what backend language are you using? – indubitablee Jan 02 '15 at 13:56
  • I think you need to prevent the original event from happening, i.e. you have to call [`.preventDefault()`](http://api.jquery.com/event.preventdefault/) on it. Also, be aware that changing `href` **after** the button has been clicked will not be refected in the current event - you would have to issue the click event on the button again (or redirect the browser to the new `href` yourself. – Robert Rossmann Jan 02 '15 at 13:58
  • move the language var into the click function – Billy Jan 02 '15 at 13:59
  • @GraceLee I am not using any backend language. I am using only HTML and javascript/jquery. – vijay Jan 02 '15 at 14:01
  • PS. Have you considered using a cookie or other kind of persistent storage to store the language preference of current visitor...? I think that would be much more easier. – Robert Rossmann Jan 02 '15 at 14:03

2 Answers2

1

You can store the value in the browser localStorage like this:

$(document).ready(function(){
   var theLanguage = $('html').attr('lang');    

   $(".homeBtn a").click(function(){
       var newHref = "home_" + theLanguage + ".html";
       $(".homeBtn a").attr("href", newHref)

       localStorage.setItem('lang', theLanguage);

   });
});

This value will persist in the application and will be accesible for you even if you refresh the page or change the page.

Then if you need to retrieve the item just do:

console.log(localStorage.getItem('lang'));
ianaya89
  • 4,153
  • 3
  • 26
  • 34
1

Using HTML and javascript your options are either cookies or hidden fields.

These are relevant posts with similar requirements:

How to get JS variable to retain value after page refresh?

or here's a simple tutorial on hidden fields:

http://www.tizag.com/htmlT/htmlhidden.php

Or browser storage as mentioned above!

Community
  • 1
  • 1
Chris
  • 805
  • 6
  • 19