Pass parameter in href html

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

Hello

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?

asked Dec 13, 2018 at 8:03

Hello

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'];

answered Dec 13, 2018 at 8:09

Hello

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'];
Hello

answered Dec 13, 2018 at 8:08

Jack BashfordJack Bashford

42k11 gold badges46 silver badges77 bronze badges

4

You can reset the href value by concatenating the existing value with the new value:

var el = document.getElementById['a'];
el.href += '?fruit=apple';
console.log[el.href];
Hello

answered Dec 13, 2018 at 8:07

Hello

Because new tab doesn't work in snippet, check it in jsfiddle.

answered Dec 13, 2018 at 8:12

MohammadMohammad

20.5k15 gold badges53 silver badges80 bronze badges

1

Would would need a way to acceess Html parameters. I dont believe its possible in html. There is a good load of Javascript Methods however.

For example:

function getUrlVars[] { 
var vars = {}; 
var parts = window.location.href.replace[/[?&]+[[^=&]+]=[[^&]*]/gi, function[m,key,value] { 
   vars[key] = value; 
}];
return vars; 

}

You would call this function like so

var fruit = getUrlVars[]["fruit"];
console.log[fruit];
//Apple

Your URL in href would look like:

a.html?fruit=Apple

However this is hardcoded, if you wanted some nice dynamics with this prehpas use angularJS to create this with.

Source

answered Dec 13, 2018 at 8:16

1

How do I pass a parameter to a link in HTML?

The % is a reserved character indicating the start of an URL-encoded character. The request parameters must be URL-encoded. The JSTL and are designed for exactly this job. As mentioned by everyone, you're however making a huge design mistake here with passing SQL strings around as request parameters.

How do I add a variable to a link in href?

How to put a variable in anchor tag

Can we pass function to href?

The anwer is: not possible.

What is href =# in HTML?

Definition and Usage The href attribute specifies the URL of the page the link goes to. If the href attribute is not present, the tag will not be a hyperlink. Tip: You can use href="#top" or href="#" to link to the top of the current page!

Chủ Đề