开发者

Javascript element is null [duplicate]

This question already has answers here: Why does jQuery or a DOM method such as getElementById not find the element? (6 answers) Closed 7 years ago.

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

the radio button

<inpu开发者_Go百科t 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?


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


You are likely running that script before the <input> element is reached in your code, so it doesn't exist when you try to access it. Make sure that your script comes after your input (or you wrap your script in a document onload event handler so that it doesn't execute until the page has fully loaded)


Put this after or below input element. The input element wasn't loaded yet and the javascript is executed so you get null.

Solution 1:

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

    show();
    </script>
    </body>
</html>

Solution 2:

Or if you preffer putting scripts in the head of html, run the function only when the page is loaded.

<html>
<head>
    <script type="text/javascript" src="yourcodes.js">
    </script>    
</head>
<body>
    <input id="supporter" value="yes" />
</body>
</html>

On your separate javascript page:

function show()
{
    var supporter = document.getElementById('supporter');
     if (supporter.value == "yes") 
     {
       alert("it works");
     }
}

//When page loaded
document.onload = function(){
    show();
};

Note: you don't have to put <script></script> in your JavaScript file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜