【问题标题】:submiting form using a button outside the form [duplicate]使用表单外的按钮提交表单[重复]
【发布时间】:2022-01-03 06:24:24
【问题描述】:

我不是编码专家,只是一个学习者 我创建了一个动态表单。生成表单时,用户应填写并提交 表格详细信息直接到谷歌表。 参考https://trickuweb.com/submit-custom-html-form-data-to-google-sheets.php [在此处输入链接描述][1] [1]:https://trickuweb.com/submit-custom-html-form-data-to-google-sheets.php 这是html

    <html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>my project</title>
<link href="" rel="stylesheet" type="text/css">

<style>
p{
color: blue;
font-size: 20px;
}

button{
color: blue;
max-width: 200px;
height: 50px;
}
</style>
</head>
</body>
<p>Fill the form below to submit to google sheet</p>
<div id ='share' style='width: 200px; height: 450px; border: 2px solid blue;' >
</div>

<div class="controls">
<button id='submit'>FORM SUBMIT</button> <br>

</div>


<!-- to access jquery-->
<script type="text/javascript" src="scripts/jquery-3.6.0.js"></script>

</body>
</html>

这里是jquery代码

$(document).ready(function(){ 
var formData =
["Name","Email","Phone"];

function createForm2(){
    $("#share").append('<form name="google-sheet">');
    for(var f=1; f<4; f++){
 
   $("#share form").append('<br><label>'+ f +'</label><input type="text" placeholder='+ formData[f-1] + '  name=' + formData[f-1] +  '  id=""/>');
   }
   $("#share form").append('<br><input type="submit" id="savebutton" value="Save" />');


    const scriptURL = 'https://script.google.com/macros/s/AKfycbwOE4ndEngGXcIerdQ708EUI0O1qdjJ7T2YTpGmzJYe_0VL3m4YlPzt9zrMl8oSewqG-Q/exec'
            const form = document.forms['google-sheet']
          
            form.addEventListener('submit', e => {
              //e.preventDefault()
              fetch(scriptURL, { method: 'POST', body: new FormData(form)})
                .then(response => alert("Thanks for Contacting us..! We Will Contact You Soon..."))
                //.catch(error => console.error('Error!', error.message))
                .catch(error => alert("An error occured while processing your request"))
            })
            
        $("#ok").on("click",function(){form.submit(); });
}

});

如果我点击表单内的保存按钮,它工作正常,但如果我点击表单提交按钮,数据没有提交? 帮忙!

【问题讨论】:

  • 表单外的按钮在哪里? id="ok" 的按钮在哪里?

标签: javascript html jquery


【解决方案1】:

如果你想使用表单外的按钮提交表单,你可以使用“form”属性

https://www.w3schools.com/html/html_form_attributes_form.asp

例子:

<form id="Form1" method="POST" action="something.php">
    <input type="text" name="name">
</form>

<input type="submit" form="Form1">

【讨论】:

  • 'krelq 非常感谢你。你的贡献。您的方法仅适用于手动创建的表单,而不适用于动态创建的表单,除非我必须调整我的代码。终于在这里找到了解决方案 [link](使用
    标签外的按钮提交表单)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-23
  • 1970-01-01
  • 2018-07-24
  • 1970-01-01
  • 2013-08-06
相关资源
最近更新 更多