2009-07-18 44 views
0

如何将ID提交给表单名称以提交某种形式?使用document.nameofformtosubmit.submit()中的变量值的javascript

function submitComment(id) 
{ 
    alert('comment on song id: '+[id]+''); 

    document.postcomment.submit(); 

} 

我希望能够提交.. postcomment43或postcomment 42 ..无论ID的价值是关节postcomment

尝试这样:

function submitComment(id) 
{ 
    alert('comment on song id: '+[id]+''); 


    var formToSubmit = 'postcomment' + id; 

    alert(''+ formToSubmit +''); 
    document.formToSubmit.submit(); 


} 

正确创建formToSubmit名但不会开火。我该如何正确放置formToSubmit变量在document.form.submit

似乎只是formToSubmit把将要寻找与名称的形式formToSubmit

回答

2

给您形式的独特ID:

<form id="postcomment42" action="..."></form> 
<form id="postcomment43" action="..."></form> 
<form id="postcomment44" action="..."></form> 

然后使用getElementById功能,以获得所需形式:

function submitComment(id) 
{ 
    var formToSubmit = document.getElementById('postcomment' + id); 
    if (formToSubmit != null) formToSubmit.submit(); 
} 

虽然我怀疑有什么问题你设计。你为什么有多种形式?你能不能有一个表单提交像注释:

<form id="postcomment" action="comment?id=42" method="post"></form> 

可不可以给的界面看起来像什么,你正在努力实现一点点更多的细节?

+0

尝试了一些东西。 (添加到问题的编辑) – ian 2009-07-18 11:43:46

0

如果你的表格只有名称,而不是ID的,那么你可以做到以下几点:

// by name 
function submitComment(id) 
{ 
    var theForm = 'postcomment' + id; 
    document.forms[ theForm ].submit(); 
} 

的很多很多的方式通过JS提交表单,但是考虑你的问题,我认为这是最适用的方式。