In our application, we use document.forms[0]开发者_运维知识库
to access the form from JavaScript. This used to work fine, till we had to introduce another form before the current form (in the page header). Obviously, now none of our form submits will work properly as it will pick up the form specified in the header.
Is there anyway, we can have document.forms[0] to reference the existing form.
The only other option we have is to reference both the forms by name and use the name in the JavaScript. But since this constitutes a considerable amount of rework, I was just thinking if the community could throw up an alternative solution.
To clarify: Using document.getElementById would be the better solution, but that is something that is planned for next major version. We would be very much stressed to have that added in the current release cycle.
You could put the form that's at the top of the page at the bottom of the HTML, and use some fancy CSS to make it show up at the top of the page. Alternatively, you may be able to use some Javascript to define the form at the top of the page after the page loads, which (i think) would make the original form show up as form[0], and the top form show up as form[1]. Even something like a simple TopFormDiv.innerHTML = 'all your form html goes here' in the body.onload might be sufficifient, of course, you can make this much more complicated.
Additionaly, you could consider "monkey patching" the document.Forms object so that the document.Forms[0] returns the form you want it to. What I'm thinking is have some code at the top of your page which switches out document.Forms[0] to the one you want it to represent, and moves everything else over 1 position. This would have to be done after the document is done loading, but before anything else on the page tries to access the form.
UPDATE
After some initial testing, it appears that calling document.forms[0] actually searches through current DOM until it returns the first form. So even if you define the form later, after the page loads, as I recommended in the first paragraph, it doesn't seem to work as you would expect. Even the "monkey patching" doesn't work as setting the value of forms[0] to some other form doesn't seem to accomplish anything as forms[0] always returns the first form in the DOM tree. So, the only way I could see accomplishing this is to define the "top" form at the bottom of your HTML, and use CSS to position it at the top of the document. For a basic example of how to position the bottom form at the top of the page see this example
I would suggest you to change your code a little bit and give id
to each form element and than use.
document.getElementById();
More information is on,
http://www.javascript-coder.com/javascript-form/getelementbyid-form.phtml
精彩评论