【问题标题】:Change HTML5 <button>'s formaction dynamically with jquery使用 jquery 动态更改 HTML5 <button> 的形式
【发布时间】:2014-03-24 11:30:07
【问题描述】:

我有一个带有不同的多个提交按钮的表单,这些按钮执行单独的操作。

其中一个按钮是添加数量字段的引导模式的一部分。当我按下此按钮时,我希望它将数量字段的值添加为 url 参数。例如,用户在数量文本字段中输入 25 并单击提交,他们应该将表单数据 POST 到页面 www.example.com/folder/?quantity=25。

不幸的是,我是 javascript 和 jquery 的新手,所以我尝试修改其他人关于如何更改表单操作以在我的按钮上工作的问题的答案。

现在我的模式和提交按钮正在工作,但按钮的形式没有改变。我还尝试使用下面的脚本更改表单的操作并从按钮中删除操作,但没有成功。

任何帮助将不胜感激。此外,我不在乎不支持旧版浏览器。如果只是 Firefox 和 chrome 支持它,那对我来说已经足够了。

<div class="modal fade bs-order-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<input type='text' name='quantity' id="quatity">
<li><button name='btn-add' id='btn-add' type="submit" form="id-details" formaction="/inventory/order/" class="btn btn-info">Add to Order List</button></li>
</div>
</div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="/static/js/bootstrap.min.js"></script>
<script src="/static/js/docs.min.js"></script>

<script>
  $(function() {
   $('#btn-add').submit(function(){
     var quantity = $('#quantity').val();
     $(this).attr('formaction', "/inventory/order/?quantity=" + quatity);
   });
  });
</script>

【问题讨论】:

    标签: javascript jquery html twitter-bootstrap


    【解决方案1】:

    问题是按钮没有提交事件 - 表单有。您要做的是修改按钮的单击事件。另外为了安全起见,我更喜欢在附加事件时使用$(document).ready()

    $(document).ready(
        function () {
            $('#btn-add').on('click', function () {
                var quantity = $('#quatity').val(); // Your ID on the "quantity" input is missing an "n"
                $(this).attr('formaction', "/inventory/order/?quantity=?quantity=" + quantity);
            });
        });
    

    最后,您可能需要添加一些基本验证,以确保文本框中的值不是空的或字母数字。

    【讨论】:

      猜你喜欢
      • 2011-12-29
      • 2015-11-01
      • 2019-05-29
      • 1970-01-01
      • 1970-01-01
      • 2016-04-05
      • 1970-01-01
      • 2010-12-28
      • 2011-11-10
      相关资源
      最近更新 更多