June 22, 2018 at 8:51 pm #49553
When I go to run 22.214.171.124 on Chrome 67.0.3396.79 I’m getting “Uncaught TypeError: Cannot set property ‘value’ of null at app.js:310” which is the line “fullName.value = ‘Zac Gordon’;” Everything else in app.js is commented out except for this:
var mainForm = document.getElementById( 'main-contact' ), fullName = document.getElementById( 'fullName' ), phonePreference = document.getElementsByName( 'contact-preference' ); fullName.value = 'Zac Gordon'; phonePreference.value = 'checked'; console.log( phonePreference );
Has anyone come across this?June 23, 2018 at 10:51 am #49590Zac GordonKeymaster
The error is saying that fullName is null. Try logging the vars that you set with console log. One possibility is that there is no element on the page with that class that is being selected.
Is this happening in the example code without any changes?June 25, 2018 at 3:00 pm #49704
No, the example files work as-expected after reviewing the originals again. I may have had something modified in my earlier set of example pages as I was working through the videos. So it was probably just user error.
Question: just for clarification, when trying to change an input field’s value via JS, it ONLY works when the input element has an id assigned to it (using document.getElementByID), correct? I tried a few other forms using document.getElementsByName (because their input elements didn’t have IDs) but it didn’t work.June 25, 2018 at 3:08 pm #49714Zac GordonKeymaster
The selecting of elements from the DOM is separate from changing the value attribute.
When selecting with getElementsByName it will return an array of values, even if there is only one matching element. So you would first have to get the item from the array you want, then change the value of that element.
It is likely not working because you are trying to change the value of the array, which won’t work, rather than one of the elements in the array.
This is a good question because some selector methods like getElementById only return one value, whereas selectors like getElementsByName will return an array of values.
Hope this helps!June 25, 2018 at 3:12 pm #49718
I realized that as I was re-watching the video and you mentioned it at one point, but the difference wasn’t 100% clear to me until I tripped over this 🙂 Thank you!
- You must be logged in to reply to this topic.