Skip to content Skip to sidebar Skip to footer

Append Url Parameter To Href With Javascript

I'm trying to append a query string parameter to a href on a page using some JS: var url = 'http://www.sitetest.com?source=' + value; var element = document.getElementById('thislin

Solution 1:

On your test page, have you checked the console?

Uncaught ReferenceError: value is not defined

The posted code will work fine if you assign a value to the value variable.

Solution 2:

You need to assign a value to the variable "value", it is currently undefined

Uncaught ReferenceError: valueisnot defined

Example

window.addEventListener('load', function () {
  var value = "testValue";
  var url = "http://www.sitetest.com?source=" + encodeURIComponent(value);
  var element = document.getElementById('thislink');
  element.setAttribute("href",url);
});

You also want to use encodeURIComponent for any string values you are passing in a URL, to make sure it encodes special characters

Post a Comment for "Append Url Parameter To Href With Javascript"