Reputation: 1
I'm trying to capitalize the first character of a string from user input field. Below is the listener tag that collects the firstname data.
`<script>
(function () {
var element = document.querySelector('input[name="firstname"]')
element.addEventListener("blur", function(e) {
dataLayer.push({
'event': 'first_name',
'first_name': e.target.value
});
}, true);
})();
</script>`
I've tried a few variations of the below but none are working
`<script>
(function () {
var element = document.querySelector('input[name="firstname"]');
**var elementUpper = element.charAt(0).toUpperCase() + str.slice(1);**
**elementUpper**.addEventListener("blur", function(e) {
dataLayer.push({
'event': 'first_name',
'first_name': e.target.value
});
}, true);
})();
</script>`
I've also created a new tag with the below HTML which isn't working.
`function() {
var txt = {{dlv - first_name}};
return txt.replace(/\w\S*/g, function(t){
return t.charAt(0).toUpperCase() + t.substr(1).toLowerCase();
});
}`
Any guidance would be appreciated.
Upvotes: 0
Views: 50
Reputation: 44068
In the first example, use the "change"
event instead of the "blur"
event for form fields.
In the second example, the DOM object (ie element
) and the string (ie elementUpper
) have been reversed.
.addEventListener()
applies to DOM objects like:
const domObject = document.querySelector(`input[name="firstname"]`);
domObject.addEventListener("change", callback);
Furthermore, .charAt()
, .toUpperCase()
, and .slice()
should apply to e.target
.value
which is a string value created by the callback function when the event
is triggered:
const stringValue = e.target.value;
stringValue.charAt(0).toUpperCase() + stringValue.slice(1);
Place the working expressions such as the example above, within the callback function so that it is processed when the event
is triggered, in this instance that would be when the user is no longer focused on the <input>
.
The third example is so fraked it's not worth considering.
Note in the example below, under this situation this
and e.target
¹ are interchangeable in a non-arrow callback function, see this section.
¹ e.currentTarget
as well
let dataLayer = [];
const input = document.querySelector(`input[name="firstname"]`);
input.addEventListener("change", function(e) {
this.value = this.value.charAt(0).toUpperCase() + this.value.slice(1);
dataLayer.push({
event: "first_name",
first_name: this.value
});
console.log(dataLayer);
});
<label>First Name: <input name="firstname"></label>
Upvotes: 0