I'm having a little trouble with radio buttons, what am I not seeing?

I have a form with radio buttons in my html and a script to trigger an alert but the script is causing an error stating that the function is undefined what am I missing is it because it’s in codepen and needs a different approach?

code

<form class="rads">
         <label class="radio-inline">
           <input type="radio" name="optstream" onchange="handleChange(this);" value="All" checked>harry
         </label>
         <label class="radio-inline">
           <input type="radio" name="optstream" onchange="handleChange(this);" value="Online">bert
         </label>
         <label class="radio-inline">
           <input type="radio" name="optstream" onchange="handleChange(this);" value="Offline">john
         </label>
      </form> 

JS-
  function handleChange(radChange) {
    alert("value " + radChange.value);
  }

It works fine for me, can you link to your pen?

can’t say for sure unless all code is shown - could be your script and function runs before the page is fully loaded - it’s best to keep all js inside the page load event handler

document.addEventListener("DOMContentLoaded", ()=>{
// all DOM code in here
})

Alternatively, you can attach the event to the window like this:

window.handleChange = function(radChange) {
  alert("value " + radChange.value);
}

Or, even better, you could remove the onchange from your elements and attach it in javascript with a loop so you’re not repeating it every time:

var elem = document.getElementsByName('optstream');

elem.forEach(function(el){
  el.addEventListener("change", function() { 
    alert(this.value)
  });
});

Example here.


Its a twitch stream status app, I’ve tried several ways to trigger a javascript function in response to a radio button change to no avail. So I’m try the most basic way I could find.

The javascript is in a loaded check

Removing the $(document).ready(function(){} fixes it. Not sure why though. I guess the function that you link to in onchange="" should exist at the moment the DOM is being loaded?

So If I move it outside the check It should work?

Yes, it should work outside the .ready()

And it does. There should be a better solution though?

Found the reason why it doesn’t work: scope. You define the function within the callback function of .ready(), so it is only available inside that function.

I don’t quite follow?

function test(){
  var x = "Available inside this function";
  console.log(x); 
}

test(); // this will output: "Available inside this function"
console.log(x); // will output: ReferenceError: x is not defined

It works the same for functions.

I understood the scope but not quite understand why the html call would be outside it. To me the html relation seems different to something that would be outside. I can’t find the right words to discribe it.
Ok thanks, It’s not pretty but It will work for the time being.