2

I am trying to grab a query string parameter and match it to an array that is getting dynamically generated.

Edit for clarity The url will be something like www.example.com?some=stuff&id=dynamicNumber

I'm outputting my array from liquid (shopify) which seems to be rendering properly when I view the source.

My failing point seems to be setting the actual variable "soldOut", because if I put one of the actual values that I know will be in the array, it returns true.

Fiddle with a static array and functional matching: http://jsfiddle.net/zHuDU/5/

I'm just missing the querystring function because I wasn't sure how to do that with JSfiddle

Here is my code:

<script>
  var testArray = [
  // shopify liquid to generate values
{% for variant in product.variants %}
{% if variant.inventory_quantity == 0 %}
{{ variant.id }},
{% else %}
{% endif %}
{% endfor %}
    ];

function GetQueryStringParams(sParam)
{
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++) 
    {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam) 
        {
            return sParameterName[1];
        }
    }
}

var soldOut = GetQueryStringParams('id');


  if(jQuery.inArray(soldOut, testArray)!==-1)  {
      console.log("The ID was in the test array (out of stock)");
  }
  else{
      console.log("The ID wasn't in the test array (so it's in stock or I messed up)");
  }
</script>
Patrick
  • 872
  • 1
  • 5
  • 14
  • So it doesn't return false when not in the array? because the fiddle works just fine. Can you show us some examples of `GetQueryStringParams('id')`? – Spokey Dec 09 '13 at 14:26
  • Yes, the fiddle works, but when I try all the code together, it looks like GetQueryStringParams('id') isn't actually pulling the relevant info from the query string. That's what I was trying to say. I got it from here: http://css-tricks.com/snippets/javascript/get-url-variables/ – Patrick Dec 09 '13 at 14:28
  • yea if i had to guess there is something wrong with the querystring parsing. yours doesn't look bad but i would use a proven lib for this rather than debug it http://stackoverflow.com/questions/3788125/jquery-querystring – jm0 Dec 09 '13 at 14:30
  • I've tried a number of them, but I will give your link a shot. I can't help but feel I'm just doing something wrong with my syntax to create the variable. – Patrick Dec 09 '13 at 14:31
  • Try `console.log(soldOut)` and `console.log(window === top)`. – Alexey Lebedev Dec 09 '13 at 14:31
  • you surely have not seen this. http://stackoverflow.com/a/5158301/17447. please change your getParameters method – naveen Dec 09 '13 at 14:45

1 Answers1

3

soldOut is string, but the values in your array are integer. Cast soldOut to an int:

soldOut = +GetQueryStringParams('id');
Alexey Lebedev
  • 11,988
  • 4
  • 39
  • 47