# addEventListener is not a function?

**URL:** <https://community.hubspot.com/t/addeventlistener-is-not-a-function/79229>\
**Category:** CMS Development\
**Tags:** javascript\
**Created:** [April 13, 2023, 12:06am UTC](https://community.hubspot.com/t/addeventlistener-is-not-a-function/79229 "2023-04-13T00:06:51Z")\
**Posts on this page:** 1\
**Showing post:** 5

<div class="post-metadata">

**Author:** ![GRajput](https://d10pqhm3lwygmk.cloudfront.net/user_avatar/community.hubspot.com/grajput/32/102020_2.png) [@GRajput](https://community.hubspot.com/u/GRajput)\
**Post date:** [April 20, 2023, 12:11pm UTC](https://community.hubspot.com/t/addeventlistener-is-not-a-function/79229/5 "2023-04-20T12:11:27Z")

</div>

Hi @SRalston05

The error message is indicating that `sourceField` is not a valid DOM element and therefore does not have an `addEventListener` function. The `getElementsByName` function returns a collection of elements, even if there is only one element with the specified name. Therefore, you need to access the first element of the collection to attach the event listener.

Here is the corrected code:

```javascript  
window.addEventListener(‘message’, event =\> {  
if(event.data.type === ‘hsFormCallback’ && event.data.eventName === ‘onFormReady’) {  
let sourceField = document.getElementsByName(“city”)[0];  
sourceField.addEventListener(“change”, myFunction);

function myFunction() {  
let cityFieldValue = sourceField.value;  
let hiddenField = document.getElementsByName(“hidden\_city\_field”)[0];  
hiddenField.value = cityFieldValue;  
}  
}  
});  
```

In this code, `sourceField` is accessed using `[0]` to get the first element of the collection. The `myFunction` function is modified to retrieve the value of the `city` field and set the value of the hidden field named `hidden_city_field`.

Make sure to replace `hidden_city_field` with the name of the actual hidden field you want to set the value of.

Note that the `change` event is fired when the user changes the value of the field and moves focus away from the field, such as by clicking outside of the field or pressing the Tab key. If you want to update the hidden field in real-time as the user types, you can use the `input` event instead of the `change` event.

Please mark it as SOLUTION ACCEPTED if you like the solution.

Thank you!

---

_[View the full topic](https://community.hubspot.com/t/addeventlistener-is-not-a-function/79229)._
