Reputation: 55
I am very new to javascript and coding in general, and I am trying to capture the Order Number value from a hidden div on my confirmation page.
Could someone help me out? I imagine this will be very simple. Here is my code:
I am adding this to Google Tag Manager so I can send the order ID back to the ad platforms.
<!DOCTYPE html>
<div id="zGTMOrderData">
<input name="M$M$zGTMOrderData_OrderNumber" type="hidden" id="M_M_zGTMOrderData_OrderNumber" value="27664425">
</div>
<script>
var getOrderNumber = function() {
document.getElementById("M_M_zGTMOrderData_OrderNumber").value;
</script>
Upvotes: 1
Views: 1735
Reputation: 32760
If you are using GTM, you should not do custom JavaScript (that defies the purpose of having GTM). Instead, go to "variables", click "new", click "variable type", and select "DOM Element" from the list. Make sure "Selection Method" is set to "ID" and enter the id of your element.
The value will only be available for tags that fire after the element is rendered, so triggers with "DOM Ready" are a good bet (but then you have the same caveat for you custom script).
The DOM variable type will return by default the innerText (or value, in the case of form fields) of the element. You can also enter an attribute name, in which case the variable will return the value of the attribute.
Also, if you insist on custom Javascript you still need to set up a variable with GTM to catch the value, so using the built-in saves you a step.
Upvotes: 0
Reputation: 104
document.getElementById("M_M_zGTMOrderData_OrderNumber").value;
Add the return
keyword at line start to make this the return value of the function.
there are 3 general approaches you can take actually:
returning the value
var getOrderNumber = function() {
return document.getElementById("M_M_zGTMOrderData_OrderNumber").value;
direct assignment (if you just need to assign the value to variable, there isn't really need of a function right now)
var getOrderNumber = document.getElementById("M_M_zGTMOrderData_OrderNumber").value;
Assigning to a variable in the outer scope of the function
var orderNumber = null;
getOrderNumber = function() {
orderNumber = document.getElementById("M_M_zGTMOrderData_OrderNumber").value;
}
getOrderNumber()
// now orderNumber stores the computed value
Upvotes: 1
Reputation: 734
var getOrderNumber = function() { // your function is not closed
const inputValue = document.getElementById("M_M_zGTMOrderData_OrderNumber").value;
// have fun with inputValue
} // close the function
Upvotes: 0