0

I am using jquery to get the value of a text input box named with id of qty however I am not sure how to then get the value to appear in my javascript for my google analytics datalayer push.

So how do I get the value of qtyvalue to properly show in the quantity section of the below code?

 <script> require(['jquery'], function ($) { //GET VALUE OF QTY BOX qtyvalue = $("#qty").val(); $(".tocart").click(function(){ dataLayer.push({ 'event': 'addToCart', 'ecommerce': { 'currencyCode': 'USD', 'add': { 'products': [{ 'name': '<?php echo noSingleQuote($all_names);?>', // Name or ID is required 'id': '<?php echo "$google_sku";?>', // Name or ID is required 'price': '<?php echo "$google_price";?>', // Insert product price 'brand': '<?php echo "$google_site_owned_by_name";?>', // Insert product brand 'category': '<?php echo "$category_name";?>', // Insert product category 'quantity': 'qtyvalue', }] } } }); }); }); </script> 
2
  • 3
    just remove the single quotes around it in the dataLayer object (it's a variable, not a string) Commented May 9, 2019 at 15:03
  • Also, altough unrelated, you should remove the , after the last property of an object. Commented May 9, 2019 at 15:05

1 Answer 1

2

Two things:

1) 'quantity': 'qtyvalue' - you're passing a hard-coded string there, not a variable. So you will literally place the word "qtyvalue" into the field, instead of the value of the variable. You need to remove the quote marks.

2) you should probably move the qtyvalue = $("#qty").val(); line inside the "click" function...otherwise you'll get the value of the textbox as it was when the page was loaded, not when the button was clicked.

Here's an example with those two things fixed:

<script> require(['jquery'], function ($) { $(".tocart").click(function(){ qtyvalue = $("#qty").val(); dataLayer.push({ 'event': 'addToCart', 'ecommerce': { 'currencyCode': 'USD', 'add': { 'products': [{ 'name': '<?php echo noSingleQuote($all_names);?>', // Name or ID is required 'id': '<?php echo "$google_sku";?>', // Name or ID is required 'price': '<?php echo "$google_price";?>', // Insert product price 'brand': '<?php echo "$google_site_owned_by_name";?>', // Insert product brand 'category': '<?php echo "$category_name";?>', // Insert product category 'quantity': qtyvalue, }] } } }); }); }); </script> 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.