javascript - 将整个表单复制到剪贴板
问题描述
我有一个简单的表单,允许用户将不同的信息输入到多个字段中并进行计算。
HTML
<form id="coPayTotalAmount" action="">
<fieldset>
<legend>CoPay Calculator</legend>
<p>
<label for="coinsurance">Coinsurance</label>
<input class="bottom-input text-right copayCopy" id="coinsurance" name="coinsurance" type="text" autocomplete="off" value="%"/>
</p>
<p>
<label for="orderTotal">Total Deductible</label>
<input class="bottom-input text-right copayCopy" id="totalDeductible" name="totalDeductible" type="text" autocomplete="off"/>
</p>
<p>
<label for="deductible">Remaining Deductible</label>
<input class="bottom-input text-right copayCopy" id="remainingDeductible" name="remainingDeductible" type="text" autocomplete="off"/>
</p>
<p>
<label for="deductible">Total Allowable</label>
<input class="bottom-input text-right copayCopy" id="totalAllow" name="totalAllow" type="text" autocomplete="off"/>
</p>
<p>
<input type="submit" value="Calculate CoPay" />
or
<input type="reset" value="Reset" />
</p>
<p>
<label for="amount">Amount</label>
<input class="bottom-input text-right copayCopy" id="amount" name="amount" type="number" disabled />
</p>
</fieldset>
</form>
JS
(function () {
function calculateCoPay(totalDeductible, coinsurance, remainingDeductible, totalAllow) {
totalDeductible = parseFloat(totalDeductible);
coinsurance = parseFloat(coinsurance);
remainingDeductible = parseFloat(remainingDeductible);
totalAllow = parseFloat(totalAllow);
if (remainingDeductible > totalAllow) {
return totalAllow;
} else {
return ((totalAllow - remainingDeductible) * (coinsurance / 100));
}
}
var coPayTotalAmount = document.getElementById("coPayTotalAmount");
if (coPayTotalAmount) {
coPayTotalAmount.onsubmit = function () {
this.amount.value = calculateCoPay(this.totalDeductible.value, this.coinsurance.value, this.remainingDeductible.value, this.totalAllow.value);
return false;
};
}
}());
我现在想获取用户输入的信息,并允许他们使用复制到剪贴板功能来复制它,就像这样
function copyForm() {
var copyText = document.getElementById("coPayTotalAmount");
copyText.select();
document.execCommand("copy");
}
这样用户将收到如下信息:共同保险 20% 总免赔额 1000 等...
如果我采用 1 个包含唯一值(如共同保险)的 id,则此 copyForm 函数有效,但当我尝试将多个值复制到剪贴板时不起作用。
解决方案
您可以提取单个隐藏 div 中的所有信息,然后使用您的copyForm函数复制该 div。
<div style="display:none;" id="copyThis"></div>
<script>
var coinsurance=document.getElementById("coinsurance").value;
var totaldeductible=document.getElementById("totaldeductible").value;
document.getElementById("copyThis").innerHTML="Coinsurance: "+coinsurance+" Total Deductible: "+totaldeductible;
</script>
现在使用您的copyForm函数从copyThis div 复制内容。
推荐阅读
- r - R 公式是否跨包将函数和变量滞后视为变量?
- javascript - 是否可以在新标签 Chrome 扩展中预缓存 index.html、样式和脚本?
- c# - 在按键上更改 WinForm DataGridView 中的颜色
- amazon-web-services - 获取 athena 数据库中所有表的表名和行数
- bash - 如何获取便携式TOR浏览器的真实PID?
- ffmpeg - ffmpeg / python 脚本 - 它实际上在做什么吗?
- jquery - load() 和 ajax 类型 GET 有什么区别?
- react-native - navigation.navigate() 在本机反应中与 setState() 不同时工作
- node.js - Nestjs:从装饰器中检索请求/上下文
- junit - 如何针对 JSON 响应对象验证和映射来自 DB 查询的查询列