Zachrip
Zachrip

Reputation: 3382

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;
}

Upvotes: 2

Views: 2510

Answers (3)

Krishna Kumar
Krishna Kumar

Reputation: 2131

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; 
        }
    }

Upvotes: 1

Ray Toal
Ray Toal

Reputation: 88488

Assuming you have an element with the ID urlchoice (whose absence would be trivial to diagnose, but I don't think that is causing your problem because you say that check is getting called), try window.onload, not document.body.onload.

EDIT

Again, assuming the document has a radio button element with id = urlchoice, and that the script is properly invoked and is running,

Try:

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

or

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

These really should work.

Upvotes: 0

leoap
leoap

Reputation: 1729

the error points for an unidentifed element with id "urlchoice", are you sure it exists?

<body>    
    <input id="urlchoice" type="radio">

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

seems to work (i removed the double quotes of the document.body.onload = check(); line, it don't work with it

Upvotes: 0

Related Questions