Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass variable on href? [closed]

I am trying to give another variable when href=""

<a href="a.html" id="a">Hello</a>

Above is my code.

I want to pass value apple named fruit variable when going to a.html. How can I do this in JavaScript or jQuery?

like image 660
임지웅 Avatar asked Dec 13 '18 08:12

임지웅


2 Answers

The only way that JS can communicate (easily) between URLs is by creating a parameter on your link. For example:

<a href="a.html?fruit=apple" id="a">Hello</a>

On the receiving page, fetch that parameter data. If you are wanting the data embedded into the link purely via JS, you can append to the HREF using something similar to this by using the jQuery library:

$("a").attr("href", '?fruit=' + 'apple');
like image 100
Zitzabis Avatar answered Oct 19 '22 23:10

Zitzabis


Just do this on your main page:

<a href="a.html?fruit=apple" id="a">Hello</a>

And on a.html, add this code:

function getParameterByName(name, url) {
        if (!url) url = window.location.href;
        name = name.replace(/[\[\]]/g, '\\$&');
        var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, ' '));
    }

    var fruit = getParameterByName('fruit');
<a href="a.html?fruit=apple" id="a">Hello</a>
like image 29
Jack Bashford Avatar answered Oct 20 '22 00:10

Jack Bashford