提交后重新加载表单以进行锚定

时间:2016-04-20 15:13:27

标签: javascript forms

我在PHP中有一个很大的表单,有几个表,每个表计算一个(价格和数量)的总和,然后最后一个计算总数。
结构或多或少是这样的:

<form action="" id="purchase_form">
    <div id="purchase_1">
        <table>
            <input id="price_1">
            <input id="quantity_1">

            <input type="submit" name="calculate" value="Click here to calculate the partial">
        </table>
    </div>
    <div id="purchase_2">
        <table>
            <input id="price_2">
            <input id="quantity_2">

            <input type="submit" name="calculate" value="Click here to calculate the partial">
        </table>
    </div>

    <tr>
        <td id="price_sum"><?php *script* ?></td>
        <td id="quantity_sum"><?php *script* ?></td>
    </tr>
</form>

现在,当我点击提交来计算“部分”时,它同时给出了总数。我知道这不是最先进的形式,但无论如何,只是试着对此视而不见。

我想要的是,当我点击提交按钮时,重新加载页面显示我点击的表单。比如,如果我点击#purchase_1表的提交,我希望页面在#purchase_1表上重新加载,依此类推。

用javascript可以做到吗?

1 个答案:

答案 0 :(得分:0)

如果我理解你,那是不可能的。您可以在客户端进行计算,前提是它们并不复杂。如果你在后端的东西上执行了一些神奇的东西而你无法计算客户端的价格,你可以在表单上提交xhr请求(注意:表单不会像往常一样提交,所以页面赢了不能重装。

如果您选择第二个选项,完美解决方案将只检索所需的html。但这不是强制性的。在这两种情况下,您都可以使用以下代码:

var form = document.getElementById("purchase_form");
form.addEventListener("submit", function(e) {
  e.preventDefault(); // we prevent the default action, which is a submit for the form element

  var xhr = new XMLHttpRequest(); // create a new XHR object.
  xhr.open("GET", form.action, true); // open the async connection
  xhr.addEventListener("load", function() {
    var doc = document.implementation.createHTMLDocument(""); // you could use DOMParser aswell, but parsing html via DOMParser is not supported in in Safari < 7.1 and IE < 10.
    doc.documentElement.insertAdjacentHTML("afterbegin", xhr.response);

    // now you would have to retrieve the element where the partial price is displayed and insert that value to desired element.
    // you can do it like document.querySelector(desiredElement).textContent = doc.querySelector(selectorToElementToGetValueFrom).textContent 

  });
  xhr.addEventListener("error", function() {
    // error happened... you can handle the action for exception here
  });
  xhr.send(new FormData(form));
});

如果您有任何其他问题,请随时问我。

相关问题