Jayreis
Jayreis

Reputation: 287

get value from textbox via jquery

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>

Upvotes: 0

Views: 54

Answers (1)

ADyson
ADyson

Reputation: 61839

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>

Upvotes: 2

Related Questions