Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass variable value between different html pages in javascript

I want to pass the value of selected list item to the other page,means if I m selecting abc from the list then this abc value passes to the next html form and it should open that profile page only.Is there any way that I can use this variable among different html page.

$('.ui-li-icon li').click(function() {
    var index = $(this).index();
    text = $(this).text();
    alert('Index is: ' + index + ' and text is ' + text);

I want to pass the above text value to my profile.html which is having javascript function profile().So I want to pass this text in function call like profile(text);I tried declaring var text above the function call but still its not working.Pls tell me if any other way is there.

like image 699
user3415421 Avatar asked Apr 22 '14 07:04

user3415421


People also ask

How do I pass a JavaScript variable to another HTML page?

There are two ways to pass variables between web pages. The first method is to use sessionStorage, or localStorage. The second method is to use a query string with the URL.


2 Answers

You can pass the value as a url fragment.

In your on click function, open '/profile.html#'+text

In your profile.html get the url fragment.

Sample code:

To navigate to profile.html

window.location.href = '<path to profile.html>' + '#' + text;

In profile(), to get the parameter, use

var text = window.location.hash.substring(1)
like image 68
optimus Avatar answered Oct 19 '22 00:10

optimus


There are different ways to do it

Store the selected item in the cookies

 // Store it in the cookies
 document.cookie="selected=john"

// Get it in the profile.html
var cookie = document.cookie;

Store the selected item in the local storage

// Store it in the local storage
localStorage.setItem('selected', 'john');

// Get it from the local storage
var selected = localStorage.getItem('selected');

Use query parameter(Recommended)

You can pass the selected item in query parameter of profile.html?selected=john. I recommend this method. You can read the selected item by location.search

like image 28
Fizer Khan Avatar answered Oct 18 '22 23:10

Fizer Khan