Hi,

I have the following code which aims to change the color of a parent div when the user unselects the radio button. However it doesn't work.

<div class="jquerycorner"><input type="radio" name="hat" value="4" onblur="if(!this.checked) { this.parentNode.style.backgroundColor='#000000';}">10</div>

However the following code works when I try to detect radio button selection.

<div class="jquerycorner"><input type="radio" name="hat" value="1" onclick="this.parentNode.style.backgroundColor='#FFC0CB';">5</div>

Any ideas?

Dani AI

Generated

The behavior seen here is expected: blur fires when an element loses keyboard focus, not when its checked state changes. That is why the inline onblur on a radio won't reliably run when another radio in the group is selected—many radios never had focus to begin with. 's suggestion to use click works, and confirmed it, but a more robust, semantic approach is to listen for change on the radio group.

change fires when a control’s value or checked state is committed, so it reliably indicates which radio just became selected. One common pattern is to listen once on a container (event delegation) and then update the visual state of every radio in the named group so the previously selected item is cleared and the new one is highlighted.

Example pattern (no inline handlers; toggle a CSS class instead of inline styles):

const container = document.querySelector('.container'); // or document
container.addEventListener('change', (e) => {
  if (!e.target.matches('input[type="radio"][name="hat"]')) return;
  document.querySelectorAll('input[name="hat"]').forEach(r => {
    r.parentNode.classList.toggle('selected', r.checked);
  });
});

Prefer toggling classes (e.g., .selected) and style that class in CSS. If markup can be adjusted, CSS-only techniques (using :checked or :has() where supported) can avoid JS entirely; see MDN on :checked and :has(). For the event semantics read MDN on the blur event and the change event, and review event delegation guidance on MDN for scalable handlers.

Recommended Answers

All 2 Replies

nope, but will keep working on it.

why dont u rather implement a function on the onlick event.
I personally dont like using the onblur event.

Thanks Thirusha,

I indeed solved the problem using an onclick event.

Thank you!

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.