I am trying to use user inputs from a form on a HTML website as the inputs for the properties of an analytic.track() call in javascript.
HTML form code:
<form>
<label for="name">Name:</label><br>
<input type="text" id="name" name="name"><br>
<label for="email">Email:</label><br>
<input type="text" id="email" name="email"><br>
<label for="plan">Plan:</label><br>
<input type="text" id="plan" name="plan"><br>
<button onclick="submitTrack()">Submit</button>
</form>
Javascript Code:
function submitTrack() {
var object {
"nameVal" : document.getElementById('name').value,
"emailVal" : document.getElementById('email').value,
"planVal" : document.getElementById('plan').value;
};
analytics.track("Signed Up", {
userId: "1234567890",
name: object[nameVal],
email: object[emailVal],
plan: object[planVal];
});
I’m sure it’s wrong but can anyone let me know how it’s done. Much appreciated
2
Answers
For also having a dynamic approach:
You can call the function on submit
And then get an object structured with input name as key and input value as value:
You can then call the function with the object:
The problem is that you are trying to access the values of the form inputs using the
object[nameVal]
syntax. This syntax is not valid because theobject
variable is not an object. It is a JavaScript function.To fix this, you need to create an object and then add the values of the form inputs to the object. You can do this using the following code:
Once you have created the object, you can use it to pass the values of the form inputs to the
analytics.track()
function. You can do this using the following code:
This code will track the event "Signed Up" with the values of the form inputs.