Investigating radio button validation using Javascript ES6 syntax

I have been attempting to update my code to use ES6 syntax and I'm perplexed as to why my form's radio buttons and checked checkboxes are not registering as true when selected. Even if a user picks one of the options, I still receive an error message. Could you kindly assist me in identifying what I am doing wrong so I can improve my understanding?

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Validate me</title>
    <script type="text/javascript">
            validateAll =()=> {
            var formdata = document.forms[0].elements;
            var numelems = formdata.length;
            var checkboxelem = false;
            var radioelem = false;
            var msg = '';
            var radmsg = '';
            var checkmsg = '';
            var textmsg = '';
            var checker = true;
            for (let i = 0;i<numelems;i++){
                if (formdata[i].type == 'text' && formdata[i].value === ''){
                    msg += "<br>please enter your " + formdata[i].name;
                    checker = false;
                }

                if (formdata[i].type == 'radio'){
                    radname = formdata[i].name;
                    const numelems = document.getElementsByName(radname).length;
                    for (let rad=0;rad<numelems; rad++) {
                        if (radname[rad].checked === true){
                            radioelem = true;
                        }
                    }
                    if (radioelem === false){
                        radmsg = "<br>please select a " + radname;
                        checker = false;
                    }
                }

                if (formdata[i].type == 'checkbox'){
                    grpname = formdata[i].name;
                    const numelems = document.getElementsByName(grpname).length;
                    for (let chk=0;chk<numelems; chk++) {
                        if (grpname[chk].checked === true){
                            checkboxelem = true;
                        }
                    }
                    if (checkboxelem === false){
                        checkmsg = "<br>please check a " + grpname;
                        checker = false;
                    }
                }

                if (formdata[i].type == 'select-one' && formdata[i].value === ''){
                    msg += "<br>please select your " + formdata[i].name;
                    checker = false;
                }

                if (formdata[i].type == 'textarea' && formdata[i].value === ''){
                    textmsg += "<br>please enter your " + formdata[i].name;
                    checker = false;
                }

            }

            document.getElementById('err').innerHTML = msg + radmsg + checkmsg + textmsg;
            return checker;
        }
    </script>
</head>
<body>
    At least one input is required from each input type.<br><br>
    <span id = "err"></span>
    <form action = "dynamic.html" method = "post" onsubmit="return validateAll();" ><br/>
        Name:<input type = "text" name = "fullname" placeholder="Enter Full Name"/><br/>
        Gender:<br>
        Male<input type = "radio" name = "gender" value="male"/>Female<input type = "radio" name = "gender" value="female"/><br/>
        Hobbies <br/>
        Baseball <input type = "checkbox" name = "hobbies[]" value = "baseball" />  
        Football <input type = "checkbox" name = "hobbies[]" value = "football" />  
        Hockey <input type = "checkbox" name = "hobbies[]" value = "hockey" /><br/>
        Favorite Show <select name = "show">
        <option value = "">Choose Below</option>
        <option value = "ATHF">Aqua Teen Hunger Force</option>
        <option value = "Family Guy">Family Guy</option>
        <option value = "Simpsons">Simpsons</option>
    </select><br/>
    Comments<br/>
    <textarea cols = "50" rows = "6" name = "comments"></textarea><br/>
    <input type = "submit" name = "submit" value = "enter me" />
</form>
</body>
</html>

Answer №1

Looping through the string property, not considering the DOM elements:

const numelems = document.getElementsByName(radname).length;
for (let rad=0;rad<numelems; rad++) {
 if (radname[rad].checked === true){
  radioelem = true;
 }
}

It would be better written as:

const radioInputs = document.getElementsByName(radname);
const numelems = radioInputs.length
for (let rad=0;rad<numelems; rad++) {
 if (radioInputs[rad].checked === true){
  radioelem = true;
 }
}

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

Issue with handling multiple messages in WebSocket responses as Promises

In my web project using angularjs, I have the task of downloading data every second via a WebSocket. However, I encounter issues with handling multiple requests of different types. Although I utilize Promises to structure the requests, sometimes the respon ...

Trouble with fetching data for Line Chart via jQuery AJAX and ASP.NET MVC

I am working on incorporating a simple line chart from Google Charts into my project, but I am facing an issue with the data not loading correctly. I only require two values to be displayed: the hours worked and the days of the particular month. While I ca ...

Please provide clear guidance on the learnyounode assignment number 6 focused on "MAKE IT MODULAR."

I'm struggling to understand the instructions provided for this exercise. I find it difficult to differentiate between which file is considered the module and which one is referred to as the "original program file." I can comprehend the solutions give ...

The Node child process remains active indefinitely, persisting even after receiving the necessary data

Currently, I am tackling a loopback project that involves running a background job using Node child processes. As a beginner, I find the documentation somewhat perplexing. If anyone can provide guidance or suggestions, it would be highly appreciated. The l ...

What kinds of data types does MongoDB support in JavaScript?

Regarding the mongodb node client, it allows insertion of JavaScript data using the following syntax: collection.insert({ alpha: 123, bravo: "hello", charlie: [1, 2, 3], }) I am curious to know if mongo supports newer JavaScript data types ...

Seamless animation when collapsing element using angular and css exclusively

I am attempting to incorporate a collapsible feature into my application. Rather than relying on external libraries like jQuery, I want to exclusively utilize Angular. For demonstration purposes, I have created a very basic example here: http://jsfiddle.n ...

The jQuery AJAX call isn't getting the expected response

Having trouble with a specific part of an application I'm working on. I'm trying to make an AJAX request to fetch information from an XML file. The server is supposed to return the information in JSON format. I've used the same code for bot ...

Contrasting deleting a node_module folder with running npm uninstall to remove a specific package

Do manual deletion of a package directly from the node_modules folder and running npm uninstall really make any difference, considering that npm just deletes the package anyway? ...

Setting up a dropdown list with a Django variable following an AJAX request

I am facing an issue with implementing a dropdown that triggers an AJAX call when a new value is selected. In my setup, the AJAX script calls a Django view which returns a list of values. The problem arises when I try to populate a second dropdown with the ...

Trouble with selecting inputs within a Div Element

Could you please review the code below and help me understand why I am unable to retrieve the ID of the selected radio buttons using this.id? <div id="pay" class="btn-group" data-toggle="buttons"> <label class="btn btn-primary"> < ...

error: "undefined property cannot be read"

I am encountering an issue on our site where a bot is needed to work properly. The error message I am receiving is "cannot read property ´value´ of undefined". I have already set the bind_address to 0.0.0.0, but that did not resolve the issue (I also tri ...

SSE and the power of NodeJS through Express

Having trouble receiving SSE events in the browser. This is the server-side code (using Express): app.all('/callme', function(req, res){ res.writeHead(200, { 'Connection': 'keep-alive', 'Content-Type&apo ...

Exploring the Ways to Perform Mathematical Operations in HTML

I would like to display the percentage, but I am receiving values like 14.00 The expected value is 56%. 14 represents 56% of 25. Sample code: <h2>(@Model[1].filled.ToString("N2"))</h2> ...

Modifying the background image of div elements with JQuery in a loop function is ineffective when using Google Chrome

I am facing an issue in my application where I have a for loop to change the background image of two divs. The code snippet is as follows: for (var i = 0; i < length; i++) { $("div_" + (i + 1)).css("background-image", "../imageFile.png"); ...

Having trouble moving to a different component in Angular?

In my application, I am facing an issue with navigating from List to Details component by passing the ID parameter. It seems that there is no response or error when attempting to call the relevant method. Below, you can find the code snippets related to th ...

dynamically display elements within aframe based on specific conditions

In my aframe scene, there are three icosahedrons, a complex particle system, and a cursor that fuses on objects within the scene. The performance of the scene is affected when the particles are visible because the cursor attempts to fuse with every particl ...

How to interact with AngularJS drop-down menus using Selenium in Python?

I have been working on scraping a website to create an account. Here is the specific URL: Upon visiting the site, you need to click on "Dont have an account yet?" and then click "Agree" on the following page. Subsequently, there are security questions th ...

Hierarchical Navigation Panels

I am currently facing a challenge with designing a highly intricate navigation menu. The menu is structured in 3 levels with 2 parent tabs. Upon hovering over any tab, the user should be able to view its corresponding child navigation levels, and when not ...

What is the best way to calculate the total of values in a JavaScript object?

In my array, I have a list of items with prices that I am attempting to sum up. Here is how it appears in the Chrome developer tools: (3) [{…}, {…}, {…}]0: {ID: 1, ProductName: " New phone 1", Price: "€ 600"}1: {ID: 3, ProductNa ...

Refreshing pane content within Kendo UI Splitview

I am utilizing the Kendo UI splitview. In my setup, I have configured one pane on the left for navigation and another pane on the right for content display. The left pane contains 4 navigation links structured as follows: <div data-role="pane" id="si ...