0

I'm trying to create a URL parameter on one page and then read it back on the other page using JavaScript. Everything works beautifully until I realized that once a term is used, the same page won't update to the current code used in the page from the editor. For example, I used the term "dog" when I hadn't added any UI to the page. After adding some UI, I used the same term and nothing had updated. Then I tried another, random term and it showed up with the UI.

Here is the code on the first page, which directs to the search page:

function submitSearch(){
  var trm = document.getElementById("searchFld").value.toLowerCase();
  window.location = '/search.html?term='+trm;
}

Here is the code on the second page (The function load is called onload by the body):

var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = decodeURIComponent(window.location.search.substring(1)),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : sParameterName[1];
        }
    }
};

function load(){
var trm = getUrlParameter('term');

document.title = 'Search for "' + trm + '"';
}

Hope I've been clear enough in explanation... Thanks!

Collin
  • 487
  • 1
  • 6
  • 18

1 Answers1

0

Try using the following:

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, " "));
}

function load(){
var trm = getParameterByName('term');
document.title = 'Search for "' + trm + '"';
}

window.onload = function() {
  load();
};

Source of the code for getting parameters.

Community
  • 1
  • 1
Kairat
  • 790
  • 3
  • 7