1

I'm having trouble with a shopping cart that changes the text "product in stock" with "out of stock" dynamically when someone increases the amount of ordered products.

The variable is generated in PHP to get the product ID as a variable name, and store the stock amount into that variable. My problem arises when I try to call that variabl in jquery in the .change function.

Here, the variable gets created by using the product ID.

    <script>
    var stock_<?php echo $arrCartItem['intProductId']; ?> = "<?php echo $arrCartItem['intStock']; ?>";
    </script>

in the HTML input field, the data is being send to javascript:

<td><input type="number" value="' . $arrCartItem['intQuantity'] . '" min="1"     class="cartQuantity" data-cartid="'.$arrCartItem['cartId'].'" data-productid="'.$arrCartItem['intProductId'].'" /></td>

for example, this creates stock_2223 when product 2223 has been added to the shopping cart, and stores the number 8 in it, which is the amount of product in stock.

Now i'm trying to call it in the .change function:

$('.cartQuantity').change(function(){

var curThis      = $(this);
var intQuantity  = $(this).val();
var intCartId    = $(this).data('cartid');
var intProductId = $(this).data('productid');

if (intQuantity > stock_XXXX) 
{
    // not enough in stock
    alert("not enough in stock");
}
else {
    alert("enough in stock");
}

when I try anything like:

var intProductId = "stock_"+intProductId;

result in jquery returning the string "stock_2228" instead of the variable which contains "8".

My question is, how can I replace stock_XXXX with the number of the item in the shopping cart, in thase case, I would get stock_2223 without physically typing it in the code, and thus giving jquery the number "8" in the if statement.

is it possible to create the variable name by typing the first part of the variable name, stock_, and let the second part be created by the variable intProductId? Hope you can answer my question!

1
  • no, javascript does not have variable variables. However if the data you want is in a form input, just use $('some identifier').val(); Commented Aug 8, 2014 at 12:04

1 Answer 1

1

solution is

window['your_dynamic_var_name'];

try this

var stock_qty = window["stock_"+intProductId];

Example

Example 2 : as op's requirement

Sign up to request clarification or add additional context in comments.

1 Comment

Amazing, so simple, and works! Thank you very much for your quick reply!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.