javascript - 表单提交未包含在表单中的输入元素

标签 javascript html forms

我有一个网页,其中表单输入元素位于不同的位置,并且不能物理地包含在同一个表单中。在表单提交中包含这些输入值的最佳方法是什么?

请注意,我想执行实际的帖子提交,而不是 AJAX 提交。

最佳答案

向表单添加一个 onsubmit 处理程序,并在该处理程序中将各种输入的值复制到表单中的隐藏输入。

但是请注意,这(显然)不适用于关闭了 JavaScript 的用户。

<form id="mainForm" action="yoururl">
   <!-- visible form fields here, then hidden
        fields to hold values from non-form fields -->    

   <input type="hidden" id="field1" name="field1">
   <input type="hidden" id="field2" name="field2">
   <input type="hidden" id="field3" name="field3">
   <input type="hidden" id="field4" name="field4">
</form>

<!-- other fields to be submitted with mainForm -->    
<input type="text" id="displayfield1">
<input type="text" id="displayfield2">
<input type="text" id="displayfield3">
<input type="text" id="displayfield4">

<script>
   document.getElementById("mainForm").onsubmit = function(e) {
       e = e || window.event;
       var theForm = e.target || e.srcElement;

       // could copy fields across manually, one by one:
       document.getElementById("field1").value =
                             document.getElementById("displayField1").value;

       // or you could copy based on matching field ids:
       var fields = theForm.getElementsByTagName("input"),
           i,
           df;

       for (i=0; i < fields.length; i++) {
           if (fields[i].type === "hidden") {
              df = document.getElementById("display" + fields[i].id);
              if (df != null)
                 fields[i].value = df.value;
           }
       }

       // could return false here if there was some failed
       // validation and you wanted to stop the form submitting
       return true;
   };
</script>

对于有点丑陋的代码感到抱歉 - 只是从我的脑海中抽出一些东西。如果您有兴趣,您可以在大约三行 jQuery 中完成上述所有操作...

关于javascript - 表单提交未包含在表单中的输入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8407389/

相关文章:

html - Golang GAE - HTML 模板未将链接正确插入网页

jquery - 防止 div 在使用 jquery 切换时被推下

javascript - 带有 Formik 的 React-Native 选择器

javascript - jQuery 无法在 Wordpress 中工作 - 默认情况下工作

javascript - 如何在CKEditor中添加浏览器服务器上传图片

javascript - 尝试编写代码来汇总复选框标签文本的美元值(value)

HTML 电话 : link for private calls

html - 在 HTML 表单或输入中隐藏边框

javascript - HTML/Javascript 表单自动重置

javascript - 试图理解这个 location.href.match JS RegExp 部分