Hi,

I'm having trouble getting access to a Radio button. I found on the internet that I can use:

document.form_name.radio_name[number].checked = true;

So I'm doing that:

document.hitForm.Answer_1[0].checked = true;

But it isn't working. I have included a picture of the Chrome Dom inspector.

Pic

The first circle points to the form the radio button is in.
The second and fourth circle are the same <p> where tho radiobuttons are in with the same name. The third circle is an example of the radio button I need access to and I want to put it checked.

Can anyone help me out on this?

Dani AI

Generated

Common reasons a radio input looks unreachable are: the inputs are actually outside the form (misplaced closing tag), the script runs before the DOM exists, multiple elements share the same name in different parts of the page, or dot-notation form access fails because the name is not a valid identifier. marked the thread solved, but these checks help make any solution robust.

A modern, reliable selector is querySelector/querySelectorAll. Selecting by form, name and value avoids ambiguity and lets the code both set the radio and fire events:

var r = document.querySelector('form[name="hitForm"] input[name="Answer_1"][value="0"]');
if (r) {
  r.click(); // sets the radio and triggers native events
}

If code must wait for the DOM, wrap it in a DOMContentLoaded listener:

document.addEventListener('DOMContentLoaded', function () {
  var r = document.querySelector('input[name="Answer_1"]');
  if (r) r.click();
});

If using jQuery (as suggested), a compact approach is:

$('form[name="hitForm"] input[name="Answer_1"]').first().prop('checked', true).trigger('change');

Troubleshooting checklist:

  • Confirm the inputs actually have name="Answer_1" and are inside the intended form.
  • Inspect the DOM after any dynamic build; selection may need to run after insertion.
  • Remember setting .checked programmatically does not always fire event handlers; use .click() or dispatch an event if handler execution is required (see the Event constructor docs).
  • Use the console to inspect document.getElementsByName('Answer_1') or document.querySelectorAll(...) to verify what the page exposes.

Reference: Document.querySelector and Event constructor.

Recommended Answers

All 2 Replies

I would just have used the jQuery selector to select the radiobutton with the corresponding name :) but I'm a jQuery freak as well so don't listen to me x)

Problem has been solved!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.