【问题标题】:HTML form with dynamic action (using JavaScript?)具有动态操作的 HTML 表单(使用 JavaScript?)
【发布时间】:2011-06-23 17:34:32
【问题描述】:

我想创建一个这样的表单:

  1. 在表单的输入中输入您的 ID 号并提交。
  2. 表单的操作类似于/account/{id}/

有人告诉我 JavaScript 是实现这一目标的唯一方法(请参阅 here),但是如何实现呢?

【问题讨论】:

  • 我认为您正在寻找像 account.php?id=33 这样的 GET 请求?
  • 不,我正在寻找像account/33这样的POST请求
  • 就因为你提到了w3schools:w3fools.com

标签: javascript html forms action


【解决方案1】:

使用jQuery 可能看起来像这样:

$('#inputAccount').change(function () {
    $('#myForm').attr('action', 'http://www.example.com/account/' + $('#inputAccount').val());
});

这应该会在输入元素中的文本更改时更改表单的操作。您也可以使用.blur() 而不是.change() 在焦点离开输入元素时执行操作,因此它不会一直在变化,等等。然后,当提交表单时,它应该提交到任何最后放置在其 action 属性中。

【讨论】:

  • 我建议在这种情况下进行模糊处理。潜在的无限循环,对吧?
  • @D_N:也许不是无限循环,但我认为你可能是对的,模糊是最好的。我在模糊中看到的唯一问题是,如果某些浏览器在返回时从输入元素内提交表单,而没有从技术上离开该元素。
【解决方案2】:
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $(frm.txt).keyup(function(){
            $(frm).get(0).setAttribute('action', '/account/'+$(frm.txt).val());
        });
    });
    </script>
</head>
<body>
<form id="frm" action="foo">
    <input type="text" id="txt" />
    <input type="submit" id="sub" value="do eet" />
</form>

【讨论】:

  • 不明白为什么不……试一试:)
【解决方案3】:

您可以在 JavaScript 中执行类似的操作。根据选中的单选按钮(在这种情况下,但它可能是另一个表单元素),它将选择一个操作或其他:

<script type="text/javascript">
function OnSubmitForm()
{
  if(document.myform.operation[0].checked == true)
  {
    document.myform.action ="insert.html";
  }
  else
  if(document.myform.operation[1].checked == true)
  {
    document.myform.action ="update.html";
  }
  return true;
}
</script>

<form name="myform" onsubmit="return OnSubmitForm();">
   name: <input type="text" name="name"><br>
   email: <input type="text" name="email"><br>
   <input type="radio" name="operation" value="1" checked>insert
   <input type="radio" name="operation" value="2">update
   <p>
   <input type="submit" name="submit" value="save">
   </p>
</form>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多