3
function getCode() {
    if (window.location.href.indexOf("?discount=")) {
        var url = (document.URL);
        var id = url.substring(url.lastIndexOf('=') + 1);
        window.alert(id);
        return true;
    } else {
        return false;
    }
}

Purpose: When people go to our "Service Request" page using a QR code that has a substring of ?discount=1234. I have been testing by creating an alert box with the discount code showing. Eventually I want to be able to populate that "1234" automatically into a "Discount Code:" text field on page load.

The above is a mixture of a few suggestions when I researched it.

Result: Going to example.com/serviceRequest.html?discount=1234 gives me the appropriate alert "1234", as I want... Going to example.com/serviceRequest.html gives me the alert http://example.com/serviceRequest.html, but I don't want anything to happen if "?discount=" is null.

Any suggestions?

jnthnjns
  • 8,962
  • 4
  • 42
  • 65

6 Answers6

4

indexOf returns -1 if the search pattern doesn't exist. In JavaScript, anything not a 0 or false or undefined is considered true.

So your line of:

if(window.location.href.indexOf("?discount=")) {

Would better search as:

if(window.location.href.indexOf("?discount=") > -1) {
creanium
  • 647
  • 4
  • 17
1

Try changing your if-statement to:

if(window.location.href.indexOf("?discount=") != -1)
Travesty3
  • 14,351
  • 6
  • 61
  • 98
1

Look up the documentation for ".indexOf". It returns -1 for not found and >= 0 if it is found.

...indexOf("?discount=") >= 0
Louis Ricci
  • 20,804
  • 5
  • 48
  • 62
1

substring and indexOf return -1 if the text is not found, so you can test for this. E.g.

   function getCode() {
        if(window.location.href.indexOf("?discount=") != -1) {
            var url = (document.URL);
            var id = url.substring(url.lastIndexOf('=') + 1);
            window.alert(id);
            return true;
        }
        else {
            return false;
        }
    }
lamplightdev
  • 2,041
  • 1
  • 20
  • 24
1

You just need to test the indexOf value:

function getCode() {
  if (window.location.href.indexOf("?discount=") !== -1) {
    var url = (document.URL);
    var id = url.substring(url.lastIndexOf('=') + 1);
    window.alert(id);
    return true;
  }
  else {
    return false;
  }
}
ron tornambe
  • 10,452
  • 7
  • 33
  • 60
0

So the quick and dirty answer would be

var discount = window.location.search.split("?discount=")[1];
alert(discount);

But this doesn't take into account the occurence of other query string parameters.

You'll really want to parse all the query parameters into a hash map.

This article does a good job of showing you a native and jQuery version.

http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html

Kris Gray
  • 378
  • 1
  • 7