Fill in a radio button automatically

While training on a website, I attempted to automatically fill a radio button type. However, when I used the code from the site in my Google Chrome console, it returned undefined.

The website:

the html: view-source:https://benalexkeen.com/autofilling-forms-with-javascript/

I am trying to select the third radio button using this code:

var radioElements = document.getElementsByName("input3");

    for (var i=0; i<radioElements.length; i++) {
      if (radioElements[i].getAttribute('value') == 'Radio3') {
        radioElements[i].checked = true;
      }
    }

Output:https://i.sstatic.net/9TjLg.png

Even after attempting to adjust this code for another website, I continue to receive an undefined output.

Answer №1

Perhaps this information will be of assistance. It's easy to confuse attribute values.

let radioOptions = document.getElementsByName("input3");

    for (let j=0; j<radioOptions.length; j++) {
      if (radioOptions[j].getAttribute('value') == 'choice1') {
        radioOptions[j].checked = true;
      }
    }
<input type="radio" id="option1" name="input3" value="choice1">
<label for="option1">Option 1</label><br>
<input type="radio" id="option2" name="input3" value="choice2">
<label for="option2">Option 2</label><br>
<input type="radio" id="option3" name="input3" value="choice3">
<label for="option3">Option 3</label>

Answer №2

For those seeking a more straightforward solution for better readability, consider the following alternative method:

// Swap out 'var' with 'let'
let radioElements = document.getElementsByName("input3");
radioElements.forEach((input) => {
    if(input.value === "Radio3") input.checked = true;
})
<input type="radio" id="Radio1" name="input3" value="Radio1">
<label for="radio1">Radio 1</label><br>
<input type="radio" id="Radio2" name="input3" value="Radio2">
<label for="radio2">Radio 2</label><br>
<input type="radio" id="radio3" name="input3" value="Radio3">
<label for="radio3">Radio 3</label>

Regarding the use of undefined, remember that if your code lacks an explicit return value, it may default to this. Nevertheless, this does not indicate a malfunction.

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

ng-model fails to synchronize with HTML

When I click on ng-click, the model changes but the HTML remains the same... HTML <p>Reserved:<span>{{seatsInfo}}</span></p> <div ng-click="change()">change</div> JavaScript $scope.seatsInfo = 20; $scope.change = fu ...

Retrieve a subsection of an object array based on a specified condition

How can I extract names from this dataset where the status is marked as completed? I have retrieved this information from an API and I need to store the names in a state specifically for those with a completed status. "data": [ { "st ...

I am encountering an issue with the Node library puppeteer when trying to integrate it with vue.js

While following a YouTube tutorial on utilizing puppeteer in JavaScript, I encountered an issue where the page would not render even if I required the library. The problem seemed to be located right below where I imported my Vue components: <script> ...

Styling a layout with two columns, centered with an offset

I have created a layout with two columns - one on the left and one on the right, with the left column containing two rows. However, I am looking to offset the center point of the column to the right so that the left column occupies about 60% of the space ...

Is it possible for the $.post function to overwrite variables within the parent function?

Recently, I delved into the world of JavaScript and my understanding is quite limited at this point. So, please bear with me as I learn :-) I am working on a basic booking system that saves dates and user IDs in MySQL. The system checks if a particular da ...

Efficiently populating a dataTable with data using ajax

Here is the code I am using to load a data table: $(".dataTable").dataTable({"bProcessing": true, "sAjaxSource": "datatable"}); This file contains the data for the datatable: return '{ "aaData": [ [ "row 1 col 1 data", "row 1 col 2 data", "row 1 ...

Text alongside a perfectly aligned image

I'm facing a dilemma. I've been striving to replicate the layout of my training website blocks to look like this: http://prntscr.com/4cd4gm. However, aligning text and paragraphs has become an obstacle for me. Despite succeeding in aligning pictu ...

I'm looking for a solution to correct the array output from my function in node

I have a function that is currently functioning, but I am in need of proper array sorting. First, I will display my code, followed by the current output and then the desired output. Can someone help me edit my entire code and output? var app = require(&a ...

Tips for aligning elements of varying heights

Currently, I am tackling a responsive web design challenge involving floating multiple items in 4 columns side by side. The issue arises due to the varying heights of these items, causing the floating to behave improperly. Here is the current problem illu ...

The content of the HTML request may not always be displayed exactly as it appears in the browser

I've been trying to extract comments from a website using Python and urllib. Although I am successful in obtaining the HTML, I noticed that the comment section is missing. Here's what my Python code retrieves: <div data-bv-product-id="681012 ...

Setting the default value in a Reactive form on the fly: A step-by-step guide

When creating a table using looping, I need to set the default value of my Reactive Form to `Repeat` if the loop value matches a particular character, otherwise I want it to be empty. Here is my code: typescript rDefault:string = ""; create(){ ...

Why Does Angular's ngIf Always Result in a Negation to True?

Can someone please clarify this for me? I'm having trouble understanding why the *ngIf condition and else statement always evaluate to true unless I am completely mistaken. Here is the situation: I have an icon that should turn the background color t ...

Tips for stopping Angular from rendering a directive that is producing incorrect results after an error is thrown

My directives have a template and a compile function that modifies the template. Occasionally, Angular fails to recognize jQuery (and defaults to using jqLite), causing my compile to encounter errors. Despite this, Angular continues to render the directive ...

Two distinct iterations of the identical jquery version sourced from external sources

NOTE: This situation involves having two copies of jQuery with the same version number but different libraries loaded by external sources. This is distinct from the issue of using multiple versions of jQuery on a single page, as discussed here: Can I use m ...

Leveraging HTML classnames for metadata purposes

Is it recommended to use descriptive class names in HTML that fully describe its content, such as navbar-static-8 for a fixed navbar with 8 items? Alternatively, should the metadata be separated into individual attributes like type="static" items="8"? I ...

Troubleshoot: Why Equal Height Columns in Bootstrap 4 are not functioning

My design includes two columns placed side by side, each containing different content. I assumed this was a default feature in Bootstrap 4 or at least in one of its alpha versions. I have attempted the following: .equal { display: -webkit-box; di ...

Tips for designing custom dropdown menus within the WordPress menu editor

Just starting out with coding. I recently learned how to customize my website's navigation menu using menus section in the Wordpress dashboard. However, I'm struggling to create dropdown menus for child/sub pages without manually entering all th ...

Determine the scroll percentage of an element using jQuery

My goal is to create a div that animates from 0% - 100% based on the percentage of an element scrolled. I have defined some variables, but I am struggling with calculating the height as a percentage. Setting the initial width and detecting scroll are str ...

Why won't my navigation bar stay in place when I scroll down on the screen?

I'm trying to create a sticky navigation bar that becomes fixed when the user scrolls down to 200 pixels, but it's not working properly. I want it to behave like in this example: import React,{useState,useEffect} from 'react' functio ...

The functionality of RegExp is not as expected in this specific case, even though it works correctly in all

I am new to Node.js and currently transitioning from a PHP background, eager to learn more about it. My challenge involves using the following Regular Expression: /([A-Z]{2,})+/gim (identifying two or more consecutive letters). The string I am working w ...