What steps can I take to address the problem of my undefined .length value?

I encountered a length error while executing line 2 in this code snippet.

index.js:10 Uncaught TypeError: Cannot read property 'length' of undefined"

Sample Code:

<div class="formCustomerName">
         <label>Name:</label>
         <input type="text" id="customerName" placeholder="Name" value="" 
required>
</div>



let name = document.getElementById('customerName').value;

form.addEventListener('input', pushData, false);{
    if (name.value.length >= 0) {
        btn.setAttribute('disabled', 'disabled')
        document.getElementById('submitInput').innerHTML = ("Hello If statement here!")

    } else {
        document.getElementById('submitInput').innerHTML = ("Hello Else statement here!")
        btn.removeAttribute('disabled');
    }



function pushData() {

Answer №1

You assigned the value of customerName to a variable named name.

Later on, you attempted to access name.value.length, which is basically

document.getElementById('customerName').value.value.length

Since the value property does not have another nested value property, it results in undefined and triggers an error.

To fix this issue, simply remove .value from the definition of the name variable:

let btn = document.getElementById('submitButton');
let form = document.getElementById('form');
let name = document.getElementById('customerName');

form.addEventListener('input', pushData, false); 

function pushData(){
  if (name.value.length >= 0) {
    btn.setAttribute('disabled', 'disabled')
    document.getElementById('submitInput').innerHTML = ("Hello If statement here!")

  } else {
    document.getElementById('submitInput').innerHTML = ("Hello Else statement here!")
    btn.removeAttribute('disabled');
  }
}
<form id="form">
  <div class="formCustomerName">
    <label>Name:</label>
    <input type="text" id="customerName" placeholder="Name" value="" required>
    <button id="submitButton">Submit</button>
    <div id="submitInput"></div>
  </div>
</form>

Answer №2

Your current code looks like this:

const username = document.getElementById('customerName').value;

This means that username holds the value of the element with ID customerName.

username.value.length >= 0

translates to element.value.value.length. To fix this, your condition should be:

username.length >= 0

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why is it necessary to decode JSON stringified objects in Vue props?

When passing a stringifyed object via props to a component, it seems like there is an issue with the data transformation. <my-component :filter="stringobject" ></my-component> stringobject = "{"search_text":"(ciCl ...

Arrange divs on the screen in a specific formation

I am exploring ways to position specific divs in the middle of the screen to create a pearl necklace-like shape. The desired shape is as follows: 0 0 0 0 0 0 0 0 0 0 My aim is to achieve this using jQuery on a mobile ...

Exploring sections of a GLTF import within the primary rendering loop (apologies for any beginner questions)

As a Unity developer venturing into learning Three.js, I've come across a seemingly simple yet frustrating issue. My goal is to import and animate a 3D logo consisting of four separate meshes (elem1 to elem4) in my Three.js application. After exporti ...

Is there a method to accurately detect the rendering of individual elements within a React Component, rather than the entire component itself?

While it's known that Components rendering can be detected through React's Developer Tool, I came across other methods in this source. However, what I'm specifically interested in is detecting the rendering of individual elements within a Co ...

Tips on adding an image using Reactjs

I am currently working in Reactjs with the Next.js framework. I am attempting to upload images using Axios (POST method API) and will be utilizing an "api in PHP". Could someone please guide me on how to achieve this? I have tried the code below, but it&ap ...

Is there a way to slow down the falling effect on my navigation bar?

As I was working on my personal website, I had a creative idea to add a falling-down animated effect instead of keeping the layout fixed. Utilizing bootstrap for navigation, I encountered some difficulty in controlling the speed of the falling effect. Any ...

Having trouble getting CSS Animation to work in a React project?

I am currently developing a Next.js application using React. const partyButton = useRef(null) const handleParty = () => { setTimeout(() => { partyButton.current.classList.add('party-time'); console.log(party ...

Utilizing PHP, Javascript, and jQuery in mobile technology gadgets

Can anyone recommend mobile technology products that have been developed using PHP, Javascript, and jQuery? What are the newest mobile products available on the market that have been built using these languages? Do popular devices like iPhone, BlackBerry ...

Issue with formatting and hexadecimal encoding in JavaScript

I am currently developing a LoRaWAN encoder using JavaScript. The data field received looks like this: {“header”: 6,“sunrise”: -30,“sunset”: 30,“lat”: 65.500226,“long”: 24.833547} My task is to encode this data into a hex message. Bel ...

Using AngularJS, learn how to populate array objects within a JSON object

I'm trying to load array objects from a multi-select control, then populate a model object called "name" with its name and age values. After that, I want to load an array from a select element into the model object. However, the ng-model directive on ...

After a period of running NodeJS and AngularJS together, I am encountering the net::ERR_CONNECTION_RESET error

My setup includes Express with NodeJS and AngularJS on the front-end. However, after performing a series of actions such as adding data, updating records, and showing a list, I encounter the error net::ERR_CONNECTION_RESET. Interestingly, this error only o ...

Angular JS may encounter a cross domain problem when attempting to post on a third-party website

HTML Code: <div ng-app="myApp" ng-controller="myController"> <div> <input type="button" data-ng-click="submit()" ...

Click on the button to reveal the hidden content within the div, and then smoothly scroll down to view

I have a footer div that is present at the bottom of every page on our site. I've added a button to expand this div, but I'm looking for a way to automatically scroll the page down so that the user can view the expanded content without manually s ...

Vue- async function results in a Promise object with a status of <pending>

Hey everyone, I could use some assistance with my Vue code. Here's the issue: I'm attempting to retrieve data (specifically anime) from an online anime API. In my project, I have two files: Anime.vue (the view page) and getAnime.js (which house ...

Leverage JavaScript to retrieve the number of active Ajax requests in JSF

When running Selenium tests using JS, I want to ensure that there are no active Ajax requests. While I can successfully extract the amount of active Ajax requests for jQuery and PrimeFaces, I am facing some issues with JSF. String jsPF = "return PrimeFace ...

Maintain user input within the table following a page refresh

I have been working on developing a table that allows users to edit it. I successfully created a script that adds comments to the table, but unfortunately, these comments disappear when the page is refreshed. I understand that I may need some additional to ...

Implementing mouse hover functionality in a VueJS component within a Laravel application

I am facing an issue with my mouse hover functionality while working on Laravel. The Vue file I am using is located in resources/js/Dashboard.vue I have attempted to replace v-on:mouseover with @mouseover but the problem persists. When I hover over the ...

Jade incorporates a template that is dependent on a variable

Is there a way to incorporate a template that is dynamically named based on a variable? For example: include= variableTemplateName ...

Arrange data in JSON file based on job title (role name) category

My current code successfully outputs data from a JSON file, but I'm looking to enhance it by organizing the output based on the "Role Name". For example, individuals with the role of Associate Editor should have their information displayed in one sect ...

Error received - CORS request denied on Firefox browser (Ubuntu)

I encountered a CORS error (CORS request rejected: https://localhost:3000/users) while attempting to register a new user. This issue arose from content in the book Building APIs with node.js, Chapter 12. I am currently using Firefox on Ubuntu and have tr ...