Search code examples
javascriptradio-buttonchecked

I keep getting this error in javascript? (radio, checking them in javascript)


For some reason I keep getting this error, I don't know why.

Uncaught TypeError: Cannot set property 'checked' of null js.js:4
check js.js:4
(anonymous function)

Here is my code:

document.body.onload="check()";
function check()
{
document.getElementById("urlchoice").checked=true;
}

Solution

  • First check if document.getElementById("urlchoice") is null or not.

        window.onload = check;
    
        function check(){
            if(document.getElementById("urlchoice")!=null){ // available
               document.getElementById("urlchoice").checked = true; 
            }
        }