Having trouble accessing JavaScript Form Elements through Form Variable

For username validation in a form using JavaScript, I'm attempting to access the Label tag within the Form tag. If the Regex matches, then display an error in the Label; otherwise, hide it. However, when I try to modify the text in the text field, I encounter the following error:

Uncaught TypeError: can't access property "style", document.forms.form1.uNameError is undefined

Example code snippet:


        <body>
        <form name="form1">

            // few code here

            <div class="main">
                <input type="text" id="uname" name="username" onchange="checkUsername()">
                <label id="uNameError" style="color: red;">Incorrect name</label> 

            //few code here

            </div>
        </form>

        <script>
             var form=document.forms['form1'];

            function checkUsername() {
                
                let username=form["uname"].value.trim();
                let validate= /[^a-zA-Z\s]/ig.test(username);
                
                if(validate===true){
                    form["uNameError"].style.display="inline";
                    
                }else {
                    form["uNameError"].style.display="none";
                }

            }
        </script>

        </body>
    

Is there a way to effectively reuse the form variable in this scenario?

Answer №1

Here is a detailed explanation:

<form name="form1">
  <input type="text" id="uname" name="username">
  <label id="uNameError" style="color: red;">Incorrect name</label>
</form>
<script>
  var form = document.forms['form1']
  console.log(form.elements.length)
</script>

Upon running the code above, it's observed that the document.forms.elements only has a length of 1 despite having both label and input elements. This discrepancy occurs because:

Only certain tags can be accessed using document.forms:

<button>
<fieldset>
<input> (excluding "image" type inputs for historical reasons)
<object>
<output>
<select>
<textarea>

The absence of label in this list explains why it doesn't register. For further insights, refer to this link.

Possible Solutions:

  1. Replace label with output for the current code to function properly.

    <form name="form1">
                <input type="text" id="uname" name="username" onchange="checkUsername()">
                <output id="uNameError" name='uNameError' style="color: red;">Incorrect name</output> 
    </form>
    
    <script>
            var form=document.forms['form1']
    
            function checkUsername() {
                
                let username=form["uname"].value.trim();
                let validate= /[^a-zA-Z\s]/ig.test(username);
                
                if(validate===true){
                    form["uNameError"].style.display="inline";
                    
                }else {
                    form["uNameError"].style.display="none";
                }
    
            }
        </script>

  2. Access the label by referencing its id.

<form name="form1">
  <input type="text" id="uname" name="username" onchange="checkUsername()">
  <label id="uNameError" style="color: red;">Incorrect name</label>

</form>

<script>
  var form = document.forms['form1'];

  function checkUsername() {

    let username = form["uname"].value.trim();
    let validate = /[^a-zA-Z\s]/ig.test(username);
    let uNameError = document.getElementById('uNameError')
    if (validate === true) {
      uNameError.style.display = "inline";

    } else {
      uNameError.style.display = "none";
    }

  }

</script>

Answer №2

When working with document.forms, it's important to note that it only supports form elements such as input and button. Check out this link for more information.

If you want to access the label element directly...

1 ) ... You can use document.forms in the following way:

form["uname"].labels[0] 
// Note!! 
// Make sure to establish a connection between label and input by adding a for attribute for="uname" inside the label element. 'uname' is the id of the input element. This will allow you to get the label using .label[0].

or

2 ) ... Select it using the previously declared form:

form.querySelector('#uNameError');

or

3 ) ... Access it using nextElementSibling:

form["uname"].nextElementSibling

This will provide you with the necessary access to the label.

Therefore:

<body>
    <form name="form1">
            <div class="main">
                    <input type="text" id="uname" name="username" onchange="checkUsername()">
                    <label id="uNameError" for="uname" style="color: red;">Incorrect name</label>
            </div>
    </form>
    
    <script>
            var form=document.forms['form1'];
    
            function checkUsername() {

                let username=form["uname"].value.trim();
                let validate= /[^a-zA-Z\s]/ig.test(username);
                if(validate===true){
                    form["uname"].labels[0].style.display="inline";
                    // or
                    // form.querySelector('#uNameError').style.display="inline";
                    // or
                    // form["uname"].nextElementSibling.style.display="inline";
                }else {
                    form["uname"].labels[0].style.display="none";
                    // or
                    // form.querySelector('#uNameError').style.display="none";
                    // or
                    // form["uname"].nextElementSibling.style.display="none";
                }
            }
        </script>
    
    </body>

Off topic suggestion: Consider using onkeyup instead of onchange and enhancing your regex structure.

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

Does modifying data from an AngularJS service update the original data within the service?

Accidentally, I managed to create something that works but feels like it shouldn't! Essentially, I have a JSON data with a list of items that can be selected by the user, modified, and then saved. Here is a simplified version of the code: app.service ...

Trouble accessing files in the assets folder of Angular 2

I am encountering a 404 error when attempting to access a local file within my application. I am unable to display a PDF that is located in a sub-folder (pdf) within the assets folder. I am using CLI. <embed width="100%" height="100%" src="./assets/pdf ...

Having trouble getting getStaticProps to display JSX in Next.JS

I'm currently facing an issue with rendering basic data from a locally hosted Strapi API in my Next.js project. Although the data is successfully logged in the console, I am unable to map it into JSX. Below is the API get function: export async func ...

Utilizing multiple materials with a single mesh in three.js: A comprehensive guide

I am facing a major issue with three.js: My goal is to create a simple cube with different colors on each face. I attempted to achieve this using the following code snippet: // set the scene size var WIDTH = jQuery('#showcase').width() - 20 ...

Dealing with Unreliable Data in Scatter Plots using React and HighCharts

Initially, I utilized line charts for my data visualization needs. However, I now require multiple data points on the same X-Axis with tooltips, which has led me to discover HighCharts behavior: "In a line chart, by default, Highcharts will display t ...

Is it possible to adjust the center of rotation in THREE.js TrackballControls so that it is not located at the center of the canvas

I'm currently using TrackballControls within THREE.js. The issue I am facing is that the center of rotation always remains in the center of the canvas. Is there a way to adjust this and move the center of rotation upwards? Here are my failed attempts: ...

Can directive scopes (such as obj.prop) be linked together in a chain?

Here is the directive code I am currently using: template: '<form novalidate class="form-inline" ng-submit="submit($event, building)">' + '<div class="form-group">' + '<label class="form-control-sta ...

Ways to display varied JSON information on a component in Angular 4

I am facing a challenge with a reusable component that fetches data from a JSON file. I want to customize the data displayed when this component is used as a subcomponent within other components. For example, let's say we have a Banana component: @U ...

Performing a callback function in node environment

It's common knowledge that Node.js operates on a single thread and relies on asynchronous operations for I/O tasks. When Node.js is not actively running code, it actively listens for events using platform-native APIs that allow it to respond to eve ...

Utilizing WebView for Initiating AJAX Calls

One common question often asked is whether it's possible to make ajax requests using a webview. In my case, the UI will consist entirely of native Android code, but I still need to interact with the backend using ajax calls. Fortunately, I am well-ver ...

Monitoring page reload with JavaScript

Here is an example of tabbed content: <div class="tab"> <button class="tablinks" onclick="openCity(event, 'NewYork')" id="defaultOpen">New York</button> <button class="tablinks" onclick="openCity(event, 'LosAngeles& ...

Displaying Local Storage Data in Primeng Dropdown

I'm looking to implement local storage for the selected dropdown option, allowing users to see the same selection when they reload the page. Here's my dropdown: <p-dropdown [options]="languages" [(ngModel)]="selectedLanguage ...

Using Material UI with Reactjs for Background Image Mapping

I need some advice from everyone. I have an array of images and I've mapped the content, but for some reason I am unable to set a background image in the styles of a component. The other objects in the array are working as expected. {DlCards.map((mdlc ...

unable to clear form fields after ajax submission issue persisting

After submitting via ajax, I am having trouble clearing form fields. Any help in checking my code and providing suggestions would be greatly appreciated. Here is the code snippet: jQuery(document).on('click', '.um-message-send:not(.disabled ...

What is the method for rendering an ejs template from express using fetch without the need to submit a form?

login.js file: const form = document.getElementById('loginForm'); form.addEventListener('submit',async(e)=>{ e.preventDefault(); return await fetch(`localhost:8000/route`, { method: "get", heade ...

Error: The array provided to THREE.BufferAttribute must be a Typed ArraydataType

I am attempting to generate a point cloud using threejs with the following code: const pcGeom = new THREE.BufferGeometry(); const rows = 100; const columns = 3; const vertices = [...Array(rows)].map(() => [...Array(columns)].fill(0)); for(let i = 0; i & ...

The AngularJS ng-view was commented out and no errors were triggered

How can I utilize ng-view in AngularJS? I have created a folder named "detail.html" containing one HTML file. My goal is to load this file into the ng-view tag located in my index.html. However, despite commenting out ng-view, no errors are occurring. ...

Merge the xAxis functionality with Highcharts

My issue involves a chart generated by highcharts.js. The problem arises with a line chart consisting of 5 values (5 points), each displayed on the xAxis as follows: from value 1 to value 2: 0, 0.25, 0.5, 0.75, 1. I am looking to modify this display and re ...

Why is it that GetElements does not provide immediate results upon execution?

Just diving into the world of Javascript for the first time and experimenting with it on Chrome, but running into unexpected results. When I try: document.getElementsByTagName("h1") I anticipate seeing: <h1>tester h1 in body</h1> Instead, wh ...

Append a constant string to the conclusion of the route parameter

Using React Router v6.4.1, I am aiming for a consistent conclusion to a series of dynamic routes. Specifically, I want my product detail routes to always end with "-product". For example, if the path is "/shaver-900-product", it should activate my Produc ...