最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is null after getElementById? - Stack Overflow

programmeradmin0浏览0评论

Very simple error here, I'm sure, but basically I have a form with id formID and im calling it like so:

<script type="text/javascript">
    function redvalidate() {
        var form = document.getElementById("formID")
        var fields = form.getElementsByClassName("validate"),

And I'm getting the error: form is null

Can anyone spot the error?

(PS calling it onsubmit of a form)

UPDATE Ok so basically i have two onsubmit for one form which oviously doesnt work. So what I am doing is calling this function from within another...

Heres the form tag:

<form name="purchaseform" id="formID" onSubmit="RememberFormFields('purchaseform','name,email,ship_to,phone_extension,pi_name');" action="process.php" method="post" enctype="multipart/form-data">

And heres RememberFormFields:

    <script type="text/javascript">
function RememberFormFields(form,list)
{
redvalidate()

...etc... rememberformfields function ...et.c..

Very simple error here, I'm sure, but basically I have a form with id formID and im calling it like so:

<script type="text/javascript">
    function redvalidate() {
        var form = document.getElementById("formID")
        var fields = form.getElementsByClassName("validate"),

And I'm getting the error: form is null

Can anyone spot the error?

(PS calling it onsubmit of a form)

UPDATE Ok so basically i have two onsubmit for one form which oviously doesnt work. So what I am doing is calling this function from within another...

Heres the form tag:

<form name="purchaseform" id="formID" onSubmit="RememberFormFields('purchaseform','name,email,ship_to,phone_extension,pi_name');" action="process.php" method="post" enctype="multipart/form-data">

And heres RememberFormFields:

    <script type="text/javascript">
function RememberFormFields(form,list)
{
redvalidate()

...etc... rememberformfields function ...et.c..
Share Improve this question edited Sep 2, 2011 at 20:57 Jonah Katz asked Sep 2, 2011 at 20:30 Jonah KatzJonah Katz 5,29817 gold badges69 silver badges91 bronze badges 5
  • Do you have an element with id formId? – George Cummins Commented Sep 2, 2011 at 20:32
  • 5 Can you show the rest of the surrounding Javascript? The most likely cause is that the code is run before the DOM is ready and so formID is not available yet. – lonesomeday Commented Sep 2, 2011 at 20:32
  • And how about the markup of the form tag? – lonesomeday Commented Sep 2, 2011 at 20:35
  • @lonesomeday I actually have multiple on submits (not allowed to do that) so im calling within a different on submit function like so.. function redvalidate() – Jonah Katz Commented Sep 2, 2011 at 20:36
  • Post a little more of your code, still not enough to spot the problem. – nobody Commented Sep 2, 2011 at 20:41
Add a ment  | 

4 Answers 4

Reset to default 3

He's calling the function on submit of the form, so the form definitely has been loaded when the function is called. (see here http://jsfiddle/HaajY/)

I'd rather go for a misspelling in the id or something like that. Need to see more to be able to spot the problem though.

Update: You need to pass in the element as a param to the function.

this will work:

<script type="text/javascript">
function redvalidate(elem) {
var fields = elem.getElementsByClassName("validate")
alert(fields)
}

function RememberFormFields(elem,form,list)
{
    redvalidate(elem);
}
</script>
<form name="purchaseform" id="formID" onSubmit="RememberFormFields(this,'purchaseform','name,email,ship_to,phone_extension,pi_name');" method="post" enctype="multipart/form-data">
    <input type="submit"/>
</form>

see it in action here : http://jsfiddle/HaajY/2/

Assuming you have the html <form id="formID"... somewhere on your page, you simply need to defer the loading of your javascript until after the DOM is ready. You're trying to get the ID from an element that hasn't been applied to the DOM yet and therefore JavaScript sees it as NULL.

There are many ways to achieve this. You can put all your JS near the </body> tag, you can use Google's suggested deferred javascript loading practice which appends all your JS to the <head> from the bottom of the body.

This is one reason JQuery is so handy, because you can wrap your code in a $(document).ready(function(){}); block so any DOM-manipulating scripts will always work because they wait until the DOM is created before they fire. It achieves this by looking for the "DOMContentLoaded" event in modern browsers and has a doScrollCheck() function for IE which tries to scroll the body over and over - if it is scrollable, they know it's good to go. You can easily replicate this practice if you don't want to load JQuery just for this.

JQuery's DOM ready check:

if ( document.addEventListener ) {
    DOMContentLoaded = function() {
        document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
        jQuery.ready();
    };

} else if ( document.attachEvent ) {
    DOMContentLoaded = function() {
        // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
        if ( document.readyState === "plete" ) {
            document.detachEvent( "onreadystatechange", DOMContentLoaded );
            jQuery.ready();
        }
    };
}

// The DOM ready check for Internet Explorer
function doScrollCheck() {
    if ( jQuery.isReady ) {
        return;
    }

    try {
        // If IE is used, use the trick by Diego Perini
        // http://javascript.nwbox./IEContentLoaded/
        document.documentElement.doScroll("left");
    } catch(e) {
        setTimeout( doScrollCheck, 1 );
        return;
    }

    // and execute any waiting functions
    jQuery.ready();
}

return jQuery;

})();

You could also have nested forms, form inside a form.

<form>
    <form id="nested-form">
        <!-- html -->   
    </form>
</form>

In this case the nested form is not detectable with document.getElementById("nested-form") and the function will return null.

This is only because of the function getting executed before the DOM object is loaded. Use "onload" function of the body tag to call your function. Or use jQuery's $(document).ready() function which takes care of everything.

发布评论

评论列表(0)

  1. 暂无评论