[英]Copy text field dynamically with javascript
我正在使用 php(laravel/blade)循环数据,每个循环输出一个HTML
部分,其中包含不同值的输入字段。
当我单击特定 div 上的按钮时,我希望能够复制每个输入字段的值,但是我用来复制输入字段值的javascript
代码只复制一个值,无论哪个div
的按钮被点击
这是每个循环的HTML
output
<form action="{{ route('user.account.deposit') }}" method="post">
@csrf
<p>Please input amount USD worth of {{ Cryptocap::getSingleAsset(strtolower($method->name))->data->symbol }} to
deposit and send the exact same amount to the wallet address below, before clicking submit.</p>
<div class="input-group">
<input type="number" class="form-control" name="amount">
</div>
<div class="input-group">
<input type="text" class="form-control" value="{{ $method->wallet_address }}" id="{{ $method->name }}"
name="wallet_address" readonly>
</div>
<input type="hidden" value="{{ $method->id }}" name="payment_method_id">
<br>
<button type="submit" class="btn green">Deposit</button>
<a href="javascript:void(0)" class="btn btn-primary btn-xs" onclick="copy()">Copy to Clipboard</a>
<script>
function copy() {
/* Get the text field */
var copyText = document.getElementById("{{ $method->name }}");
/* Select the text field */
copyText.select();
copyText.setSelectionRange(0, 99999); /* For mobile devices */
/* Copy the text inside the text field */
navigator.clipboard.writeText(copyText.value);
/* Alert the copied text */
alert("Copied the text: " + copyText.value);
}
</script>
如果是这种情况,那么您在此处发布的整个 HTML 和 JS 都会为您的 php 循环的每次迭代输出,那么问题在于 JS 复制功能的重新定义,因为它被覆盖了。
您的解决方案可能是,您对副本 function 只有一个定义,并提供特定元素名称作为参数。
<form action="{{ route('user.account.deposit') }}" method="post">
@csrf
<p>Please input amount USD worth of {{ Cryptocap::getSingleAsset(strtolower($method->name))->data->symbol }} to
deposit and send the exact same amount to the wallet address below, before clicking submit.</p>
<div class="input-group">
<input type="number" class="form-control" name="amount">
</div>
<div class="input-group">
<input type="text" class="form-control" value="{{ $method->wallet_address }}" id="{{ $method->name }}"
name="wallet_address" readonly>
</div>
<input type="hidden" value="{{ $method->id }}" name="payment_method_id">
<br>
<button type="submit" class="btn green">Deposit</button>
<!-- Changed the onClick-Event to provide the Name as fixed parameter -->
<a href="javascript:void(0)" class="btn btn-primary btn-xs" onclick="copy({{ $method-name }})">Copy to Clipboard</a>
<!-- Move this section out of the loop and maybe at the bottom of the page -->
<script>
function copy(inputId) {
/* Get the text field */
// Changed to get the Element by the parameter containing the ElementID
var copyText = document.getElementById(inputId);
/* Select the text field */
copyText.select();
copyText.setSelectionRange(0, 99999); /* For mobile devices */
/* Copy the text inside the text field */
navigator.clipboard.writeText(copyText.value);
/* Alert the copied text */
alert("Copied the text: " + copyText.value);
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.