1

I know this question seems to be around a bit, but 90% of the answers point to a solution that is not working for me (indexof > -1).

if ( window.location.href.indexOf("product=3") > -1 || window.location.href.indexOf("product=2") > -1 ) {
    alert('success');
}else {
  alert('nothing');
}

The problem is that for product 30 this also alerts success.

Is there a simple solution that can detect an exact match in the url query string.

For example

mycoolsite.com/cart/?type=buynow&product=30

How can we check with javascript or jquery if the product equals 30?

djonamish
  • 13
  • 2
  • Welcome to Stack Overflow. I would advise looking at https://stackoverflow.com/questions/4656843/get-querystring-from-url-using-jquery Using the Top Answer, you can get all the values, so now you will be able to check if it is `3` or `30`. – Twisty Aug 09 '21 at 03:34
  • Thanks for that @Twisty, very helpful. Didn't see this one in my search. Have applied it and it works well. Thanks! – djonamish Aug 09 '21 at 03:48

2 Answers2

0

Have used the function from this post as recommended by Twisty in the comments and works well.

Get querystring from URL using jQuery

djonamish
  • 13
  • 2
0

Using the following: Get querystring from URL using jQuery

I would suggest the following:

$(function() {
  function getUrlVars(url) {
    var vars = {},
      hash;
    if (url.indexOf("?") < 0) {
      return false;
    }
    var hashes = url.substring(url.indexOf("?") + 1)
    $.each(hashes.split("&"), function(i, v) {
      hash = v.split('=');
      vars[hash[0]] = hash[1];
    });
    //console.log(url, hashes, vars);
    return vars;
  }

  var queryData;
  queryData = getUrlVars(window.location.href + "?buynow&product=3");
  console.log(queryData);
  queryData = getUrlVars(window.location.href + "?buynow&product=3&product=2");
  console.log(queryData);
  queryData = getUrlVars(window.location.href + "?buynow&product[]=3&product[]=2");
  console.log(queryData);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="result"></div>

This code has some caveats. As you can see in my tests, if you have multiple items if the same variable name or index, it will overwrite other values. Also it will not read in Arrays. You could add a check for that and write a function to handle the array portion.

If your Query Hash is always more basic, this could work well enough.

Twisty
  • 30,304
  • 2
  • 26
  • 45