问题描述
如何确保程序在返回 true 之前完全执行 GenPDF?我曾尝试使用在 GenPDF() 末尾返回一个变量来 checkForMissingFields() 函数,但程序仍然跳过 GenPDF 函数的中间部分并立即将变量返回给 checkForMissingFields() 函数。
我也试过在调用 GenPDF 函数后使用延迟,但它只是延迟了页面的重定向。
这是我使用的库:https://github.com/eKoopmans/html2pdf.js
HTML 表单:
<form
id="form"
class="ui form"
action="/PageTwo"
method="POST"
onsubmit="return checkForMissingFields()"
>
<tr>
<td>Name of checklist:</td>
<td>
<input
type="text"
name="checklist[AuditFormName]"
placeholder="Name"
id="AuditFormName"
/>
</td>
</tr>
<tr>
<td>Select Instituion:</td>
<td>
<select
name="checklist[SelectedInstituion]"
class="questionsInstitution"
id="SelectedInstituion"
onchange="updateRetailTenants()"
>
<option value="default"></option>
</select>
</td>
</tr>
<tr>
<td>Select Retail Tenant:</td>
<td>
<select
name="checklist[SelectedRetailTenant]"
class="questionsRetailTenant"
id="SelectedTenant"
style="width: 200px"
>
<option value="default"></option>
</select>
</td>
</tr>
<tr>
<td>Send a copy of this checklist?</td>
<input type="checkBox" Id="Sendcopy" value="off"
</tr>
<table>
<input
type="hidden"
name="checklist[sessionEmail]"
value="<%=sessionLogin %>"
/>
......
</form>
Javascript:
<script src='https://raw.githack.com/eKoopmans/html2pdf/master/dist/html2pdf.bundle.js'></script>
<script scr='script.js'></script>
<script>
// var form = getElementById('form')
function GenPDF(){
var name= document.getElementById('Name')
var element = document.getElementById ('form');
var opt = {
margin: 1,filename: name+'.pdf',image: { type: 'png',quality: 0.98 },html2canvas: { scale: 2 },jsPDF: { unit: 'in',format: 'letter',orientation: 'landscape' }
};
html2pdf().set(opt).from(element).save();
}
function checkForMissingFields() {
if (document.getElementById("Name").value.length == 0) {
alert("Name field cannot be blank");
return false;
}
else{
GenPDF();
return true;
}
}
</script>
解决方法
你需要 event.preventDefault();
工作 demo
// var form = getElementById('form')
function GenPDF() {
var name = document.getElementById('Name').value;
var element = document.getElementById('form');
var opt = {
margin: 1,filename: name + '.pdf',image: {
type: 'png',quality: 0.98
},html2canvas: {
scale: 2
},jsPDF: {
unit: 'in',format: 'letter',orientation: 'landscape'
}
};
html2pdf().set(opt).from(element).save();
}
function checkForMissingFields(event) {
// event.preventDefault(); // <== completely cancel submit
if (document.getElementById("Name").value.length == 0) {
event.preventDefault();
alert("Name field cannot be blank");
return false;
} else {
GenPDF();
// then submit the form
return true;
}
}
<script src='https://raw.githack.com/eKoopmans/html2pdf/master/dist/html2pdf.bundle.js'></script>
<form id="form" class="ui form" action="/PageTwo" method="POST"
onsubmit="checkForMissingFields(event)">
<input type="text" id="Name">
<button>submit</button>
</form>