Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript element is null [duplicate]

Tags:

javascript

I am a begginer at javascrit, and im trying to get a form result globaly

the radio button

<input type='radio' name='supporter' id='supporter' value='yes'>

and the javascript on the nother page

<script type="text/javascript">
function show(){
    var supporter = document.getElementById('supporter');
    if (supporter.value == "yes") {
        alert("it works")
    }
}

show();
</script>

and i keep getting an error, this: supporter is null

can please someone tell me what im missing?

like image 396
Side Avatar asked Mar 11 '26 11:03

Side


1 Answers

It will depend on when the script is executed. Javascript is executed by the browser as it is encountered, which means that if your snippet of code exists in the page before the HTML element, then at that point in time, the HTML element does not yet exist.

One solution would be to put the Javascript at the very end of the page, or move that code into the document.onload handler.

document.onload = function () {
    show();
};
like image 69
nickf Avatar answered Mar 14 '26 00:03

nickf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!