JavaScript for WordPress Forums Vanilla JavaScript Uncaught Type Error

Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
  • #49553

    When I go to run 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' )[1];
    fullName.value = 'Zac Gordon';
    phonePreference.value = 'checked';
    console.log( phonePreference );

    Has anyone come across this?

    Zac Gordon

    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?


    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.

    Zac Gordon

    Good question.

    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!


    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!

Viewing 5 posts - 1 through 5 (of 5 total)
  • You must be logged in to reply to this topic.