artaxerxe
artaxerxe

Reputation: 6411

Element uninitialized in javascript/Html when it should be

Bellow is my code snippet that present the problem what I'm facing with:

<!-- in a div -->
<a href="#" onclick="submit('/netnfork/site/billing/billing_plan_type', document.getElementById('dataForm'));" title="${addPlan}">
    <img src="/path/to/button" height="18" width="25" class="add_button"/>
</a>

<!-- bellow this, in another div -->
<form id="dataForm" action="/a/path" method="post">     
    <input type="hidden" name="page_number" id="pageNumber" value="//some JSP code"/>     
    <input type="hidden" name="row_id" id="rowId" />        
</form>

the submit function is declared in another file that is included in the beginning of this html file.

The problem is, that when I click on the link, I get this error: Uncaught TypeError: Cannot set property 'action' of null. Trying to alert the second parameter of submit function, I get null.

function submit(url, form) {
    alert(form);
    form.action = url;
    form.submit();  
}

I have an exact similar page in the same application that is working good. Can anyone explain me why I get this behavior?

I ran this page in Chrome and Mozilla, but the error occurs in both of them.

Upvotes: 0

Views: 142

Answers (2)

artaxerxe
artaxerxe

Reputation: 6411

I found the problem: above the code presented I had a div like this:

<form action="#" method="post" id="submenuForm" />.

I just put this instead:

<form action="#" method="post" id="submenuForm" > </form>, and now works good.

Upvotes: 0

epoch
epoch

Reputation: 16605

Your problem is that this (specifically getElementById):

submit('/netnfork/site/billing/billing_plan_type', document.getElementById('dataForm'));

gets evaluated before the form actually exists in the DOM, to fix the problem you will need to change it to the following:

function submit(url, formName) {
    var form = document.getElementById(formName);
    form.action = url;
    form.submit();
}

and in your HTML:

submit('/netnfork/site/billing/billing_plan_type', 'dataForm');

Alternatively you should use event listeners to handle this sort of functionality

Upvotes: 1

Related Questions