如何使用JavaScript更改表单操作
我目前的代码如下:如何使用JavaScript更改表单操作,javascript,html,forms,Javascript,Html,Forms,我目前的代码如下: <div class="fr_search"> <form action="/" accept-charset="UTF-8" method="post" id="search-theme-form"> ....... </form> </div> 如果您使用的是jQuery,那么它就这么简单: $('form').attr('action', 'myNewActionTarget.html'); 试试这
<div class="fr_search">
<form action="/" accept-charset="UTF-8" method="post" id="search-theme-form">
.......
</form>
</div>
如果您使用的是jQuery,那么它就这么简单:
$('form').attr('action', 'myNewActionTarget.html');
试试这个:
var frm = document.getElementById('search-theme-form') || null;
if(frm) {
frm.action = 'whatever_you_need.ext'
}
在这种情况下,您的表单需要有名称
:
<form action="/" accept-charset="UTF-8" method="post" name="search-theme-form" id="search-theme-form">
我想使用JavaScript更改表单的操作,这样我就可以在同一个表单中有不同的提交输入链接到不同的页面 使用ApacheRewrite将
example.com/page name
更改为example.com/index.pl?page=page name
,这也增加了复杂性。我发现更改表单的操作会导致呈现example.com/index.pl
(没有页面参数),即使地址栏中显示了预期的URL(example.com/page name
)
为了解决这个问题,我使用JavaScript插入一个隐藏字段来设置页面参数。我仍然更改了表单的操作,只是为了让地址栏显示正确的URL
function setAction (element, page)
{
if(checkCondition(page))
{
/* Insert a hidden input into the form to set the page as a parameter.
*/
var input = document.createElement("input");
input.setAttribute("type","hidden");
input.setAttribute("name","page");
input.setAttribute("value",page);
element.form.appendChild(input);
/* Change the form's action. This doesn't chage which page is displayed,
* it just make the URL look right.
*/
element.form.action = '/' + page;
element.form.submit();
}
}
形式如下:
<input type="submit" onclick='setAction(this,"my-page")' value="Click Me!" />
我想解释一下为什么仅仅设置操作不起作用。请记住,这将改变页面上的所有表单。如果我想使用jquery,如何编写不改变其他表单的代码。@enjoylife
$('#myFormId').attr('action','myNewActionTarget.html')代码>我想你的意思是文档['search-theme-form']
,文档。搜索主题表单
实际上不起作用。你可能需要定义表单名称而不使用连字符文档。表单。搜索主题表单。操作
有效
function setAction (element, page)
{
if(checkCondition(page))
{
/* Insert a hidden input into the form to set the page as a parameter.
*/
var input = document.createElement("input");
input.setAttribute("type","hidden");
input.setAttribute("name","page");
input.setAttribute("value",page);
element.form.appendChild(input);
/* Change the form's action. This doesn't chage which page is displayed,
* it just make the URL look right.
*/
element.form.action = '/' + page;
element.form.submit();
}
}
<input type="submit" onclick='setAction(this,"my-page")' value="Click Me!" />
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteRule ^/(.*)$ %{DOCUMENT_ROOT}/index.pl?page=$1&%{QUERY_STRING}