Waiting for a radio button selection to be made

I am working on a submission form that needs to have at least one radio button selected. In my code, I am able to retrieve the value of the selected radio button:

let myQuery = document.querySelector('input[name="#myName"]:checked').value;

If this value is returned (which is a string of text), can I proceed with the following:

document.getElementById("#ButtonID").removeAttribute("disabled");

Currently, my submit button is disabled, but by removing the attribute, users are able to submit their form after selecting a radio button.

How can I incorporate this into the querySelector? I already have a set of variables extracted from the .value for the selected radio button.

Thank you for your assistance :)

Answer №1

Assuming you haven't provided your HTML template, here is a possible example:

let input = document.querySelector('input[name="Name"]');

input.addEventListener("change", () => {
 console.log(input.value)
 document.getElementById("ButtonId").removeAttribute("disabled");
});
<form>
  <p>Please click on the Name:</p>
  <fieldset>
    <input type="radio" name="Name" value="Name">
    <label for="Name"> Name</label> 
  </fieldset>
  
  <button id="ButtonId" disabled>
    Submit
  </button>
</form>

If you are looking for information on how to use addEventListener, check out this link.

Answer №2

Expanding on previous responses, a form can be created where no radio buttons are selected by default but a selection is required for form submission:

The HTML structure:

<h1>test form</h1>
<form>
  <div>
    <label>
      <input type="radio" name="a-radio-group" value="first" />
      first
    </label>
    <label>
      <input type="radio" name="a-radio-group" value="second" />
      second
    </label>
    <label> 
      <input type="radio" name="a-radio-group" value="third" />
      third
    </label>
  </div>
  <div>
    <button id="button" disabled>submit</button>
  </div>
</form>

The JavaScript logic:


document.querySelector('form')
  .addEventListener('click', 
    function(event) {
      const checkedRadioInputs =
        document.querySelectorAll('input[name="a-radio-group"]:checked');

        if(checkedRadioInputs.length) {
          document
            .querySelector('button')
            .removeAttribute('disabled');
        }
    }
  );

While some aspects may already be implemented, let's focus on three key points:

  • Radio buttons should have the same 'name' attribute within a group to function correctly. This ensures that selecting one option deselects others. Explore more about radio buttons.
  • By attaching a 'click' listener to the form element, changes in the entire form can be monitored. Using this approach simplifies tracking compared to adding onChange handlers to individual radio inputs.
  • Utilizing querySelectorAll returns an array, enabling easy testing based on the array's length: absence of selection is indicated by a length of 0. Discover further details on querySelectorAll.

Answer №3

Typically, when using radio buttons, we often select one button by default. However, if you want the radio button to remain unselected initially, you can achieve this with the following code:

function hello() {
            // body...
            let button1 = document.getElementsByName("a").checked;
            console.log(button1); 

            document.getElementById("gn").disabled=false; 
             }
<form>
                <input type="radio" value="a" name="a" onclick="hello()">daknd<br>
                <input type="radio" value="b" name="a" onclick="hello()">hmm
                
                <button id="gn" type="submit" disabled>hmm</button>
            </form>

Answer №4

Your code seems correct, but there is a mistake in using '#' within the getElementById() method. Remember that while jQuery requires the '#' sign, in vanilla JavaScript, you only need to provide the ID name.

document.getElementById("ButtonID").removeAttribute("disabled");

<script>

function checkStatus(obj)
{
  
  if(obj.value != "")
  {
     document.getElementById("button").removeAttribute("disabled");
  }
}

</script>


<form id="" name="" action="" method="">

       <li><input type="radio" name="a" id="RAD_1" value="RAD_1" 
       onclick="checkStatus(this);">Hello 1</input></li>

       <li><input type="radio" name="a" id="RAD_2" value="RAD_2" 
      onclick="checkStatus(this);">Hello 2</input></li>

      <li><input type="submit" name="submit" id="button" value="Submit" disabled> 
</input>
</form>

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

Using NodeJS to Send JSON Data via HTTP POST Request

Issue with Sending JSON Data via Http Post in NodeJS const http = require('http'); const fs = require('fs'); var options = { hostname: 'www.postcatcher.in', port: 80, path: '/catchers/5531b7faacde130300002495&apo ...

Implementing an onchange function with Dojo JavaScript for selection

I am using dojo.js to create a customized dropdown box with scroll functionality, which is not available in the standard select statement. Although I have successfully implemented the dropdown menu, I am struggling to trigger a function using the standard ...

Encountered an issue when attempting to select the password field in order to log into a Google account using

Having some trouble automating the login process for my Gmail account. Managed to find the email element with an ID, but hitting a roadblock trying to locate the Password element as it doesn't have an ID. Here's what I've attempted: passw ...

Utilizing Vue CLI's sourcemaps to pinpoint the styling within a Vue component file

Currently, I am working on a Vue CLI project. After setting up the project and making some development changes, my package.json file now includes: package.json "dependencies": { "bootstrap": "^4.3.1", "core-js": "^3.0.1", "preload-it": "^1.2. ...

Incorporating the unshift method in JavaScript: A Step-by-

I'm looking to create a new function with the following requirements: Function add(arr,...newVal){ } array = [1,2,3]; add(array,0) console.log(array); //I want this to output [0,1,2,3] I tried creating the function similar to push like this: ...

What is the process for activating a button after a checkbox has been selected? Additionally, how can a value be dynamically transferred from a checkbox to the rezBlock_1 block?

What could be the reason for my code not functioning properly? How can I enable a button once a checkbox is selected? Also, is there a way to dynamically move text from a checkbox to the rezBlock_1 block? CODPEN https://codepen.io/RJDio/pen/RwPgaaZ doc ...

Utilize CamelCase in jQuery for Better Code Readability

Upon examining the jQuery source code, I noticed an interesting use of camelcase: camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); } // where: rmsPrefix = /^-ms-/, rdashAlpha = /-([\da- ...

Executing functions with iterations

Can anyone help me understand why my buttons always output 100 in the console log when clicked? Any ideas on how to resolve this issue? function SampleFunction(param){ console.log(param); } for (i = 0; i < 100; i++) { $("#btn-" + i).on('c ...

The IF ELSE Statement will consistently evaluate as true when the first IF condition is met

I am currently working on implementing an IF ELSE statement in JavaScript to change the source image of a picture when a button is clicked. The idea is that when a user clicks on a specific body type button for a car, it will update the background image wi ...

Ways to transmit data from PHP to JavaScript

I have a file called "hotlaps.php" where I've created a JavaScript script: echo "<body onload=\"myFunction(".$array_1.",".$array_2.",".$array_3.");\">"; In my "hotlaps.js" file, I have the following function: function myFunction(arr ...

Having trouble retrieving the value from the input text in a dynamically generated table

How can I retrieve values from a dynamically generated table after clicking a button? Below is the code I have implemented to create a table with input fields: function createTable(rows, cols){ var body = document.body, table = document.createEl ...

Stop the old $http request that has been running longer from responding after the newest request

Recently encountered a puzzling situation and couldn't find a solution even after thorough searching. I have a textbox where users can enter keywords to filter table data. The input element has an ng-change directive triggering the following code: r ...

Dynamic banner featuring animated text, automatically resizing divs based on width while maintaining body width

Currently, I am working on creating a banner with moving text. While I have managed to come up with a solution for implementing this effect, there are two significant issues that I am facing. The width values in pixels need to be manually adjusted based ...

Trying to showcase information received from a server using an API

For a school project, I am developing a website that can retrieve weather data (currently just temperature) based on a city or zip code from openweathermap.org using an asynchronous call. I have successfully retrieved the data from the API, but I am strug ...

The Console.log() function displays the current state and value of a promise object within the Q library

Whenever I attempt to print a promise object from Q, the result that I receive is as follows: var Q = require('q'); var defaultPromise = new Q(); console.log('defaultPromise', defaultPromise); defaultPromise { state: 'fulfilled& ...

Generate an array in JavaScript using the values from input fields

Is there a way to create a JavaScript array that stores the values of all input fields with the class 'agency_field', when there are x number of these fields in the form? I attempted to achieve this using jQuery, but encountered a syntax error. ...

Utilizing Redux dispatch to uncheck checkboxes within renderOption with Material UI Autocomplete

In the Autocomplete component, I have a checkbox that is rendered in the renderOptions prop. By using the onChange function event: object, value: T | T[], reason: string), I can retrieve the list of selected options. The value parameter will provide me w ...

Links in XML files are failing to load when exported to an HTML document

Let me start by clarifying that I am not an expert in web development or programming. My knowledge of coding is limited, and I work as a tech support agent trying to resolve issues for users. The problem we are currently facing relates to a vendor applica ...

The presence of Bootstrap remains hidden unless space is designated for it

Question about Bootstrap 5.1.3: Is there a way to hide elements on a page using the bootstrap class ".invisible" without allocating space for them? Currently, when the elements are set to visible using the class ".visible", they occupy space on the page ...

Helping React and MUI components become mobile responsive - Seeking guidance to make it happen

My React component uses Material-UI (MUI) and I'm working on making it mobile responsive. Here's how it looks currently: https://i.sstatic.net/kxsSD.png But this is the look I want to achieve: https://i.sstatic.net/kJC2m.png Below is the code ...