-2

I have no knowledge of javascript whatsoever.

Could someone write me some simple javascript code to do the following.

lets say you have the following urls:

example.com/form
example.com/form?v=China
example.com/form?v=Brazil

Could the code do the following:

if someone arrives on a page without a parameter (ie. /form) then the heading should be:

Export Your Goods

If some arrives on a page WITH a parameter (eg /form?v=China) then the heading should be:

Export Your Goods To {v}

- ie 'Export Your Goods To China'

Many thanks in advance

2 Answers2

1

You can add this <script> at the end of the page:

<script>
    var url = window.location.search;
    if (url.length) {
        url = url.replace("?v=", "");
        document.getElementById("main_heading").innerHTML = "Export Your Goods To " + url;
    } else {
        document.getElementById("main_heading").innerHTML = "Export Your Goods";
    }
</script>

Provided that you have heading as follows:

<h2 id="main_heading"></h2>
Ashutosh
  • 324
  • 1
  • 11
  • thankyou. does this script have to go at the end of the page? or can it go anywhere? – pablowilks Sep 18 '14 at 10:33
  • @pablowilks You add this `

    `

    – Ashutosh Sep 18 '14 at 10:35
  • one problem i have when i do this, is if i use a querey with spaces, such as 'export to china' then I am getting a heading like the following: export%20to%20china Is there something that can be added to tackle the white space issue? many thanks – pablowilks Sep 18 '14 at 10:49
  • @pablowilks You can use JS function `decodeURIComponent()`. See this resource: http://www.w3schools.com/jsref/jsref_decodeuricomponent.asp – Ashutosh Sep 18 '14 at 10:52
0

When you have HTML like

<h2>Export Your Goods To <span id="location"></span></h2>

Then you can set value with jQuery

$("#location").text("testing");

To get the value you can use:

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

Usage:

var value = getParameterByName('v');
$("#location").text(value);
Margus
  • 19,694
  • 14
  • 55
  • 103