Is there a better mand than this to check if a form is exists and if so submit it? Right now I'm using:
if(document.forms[0])document.forms[0].submit()
Which works, however if form[0] does not exist it throws an exception. I'm trying to keep this dynamic in the sense I don't know what the form ID or name is.
Is there a better mand than this to check if a form is exists and if so submit it? Right now I'm using:
if(document.forms[0])document.forms[0].submit()
Which works, however if form[0] does not exist it throws an exception. I'm trying to keep this dynamic in the sense I don't know what the form ID or name is.
Share Improve this question edited Nov 18, 2011 at 7:51 Claus Jørgensen 26.3k9 gold badges93 silver badges159 bronze badges asked Nov 18, 2011 at 6:44 JoeJoe 1,77210 gold badges43 silver badges60 bronze badges 2- If the problem is in JavaScript - I would not even tag this question as WP7 – Filip Skakun Commented Nov 18, 2011 at 7:19
- 1 document.forms[0] is brittle, there can be more than 1 form on a page, and if the html changes your javascript is broken. that's why i propose using Ids on the form. – Jason Commented Nov 18, 2011 at 8:01
4 Answers
Reset to default 7To avoid the exception you could do:
if (typeof document.forms[0] !== 'undefined') document.forms[0].submit();
can you add an id to the form? can you use jquery?
with id, no jquery
var form = document.getElementById('my-form');
if (form != null) {
form.submit();
}
with id & jquery
if ($("#my-form").length == 1) {
$("#my-form").submit();
}
If your only requirement is to check whether a form exists, and if so, submit the first form, you can use:
if (document.forms.length) document.forms[0].submit();
You can check for undefined
:
if(document.forms[0] != 'undefined')
document.forms[0].submit()