Reputation: 23
I am trying to select multiple text boxes at once and initiate the copy to clipboard command but only the 3rd text field always gets highlighted or selected.
HTML:
<input type="text" class="copyText" placeholder="Name"><br>
<input type="text" class="copyText" laceholder="Phone"><br>
<input type="text" class="copyText" placeholder="E-Mail"><br>
<button>Copy</button>
JS:
$('button').on('click', function () {
var copyText = $(':input[type="text"]';
copyText.select();
document.execCommand('copy');
alert('Text Copied');
});
Upvotes: 1
Views: 871
Reputation: 5260
This way is more like a hack, but works, because we have to create an element and hide it with position:absolute;left:-1000px
. The idea is to iterate over inputs and save the values into an array, then we have to store those values into a new input that is not visible. And finally we select the value of that input.
$('button').on('click', function() {
var values = $('.copyText').map(function(i, e) {
return $(e).val();
}).get();
var phantom = document.createElement("textarea");
phantom.setAttribute("style", "position:absolute;left:-1000px");
phantom.innerHTML = values.join("\n");
document.body.appendChild(phantom);
phantom.select();
document.execCommand('copy');
alert('Text Copied');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="copyText" placeholder="Name"><br>
<input type="text" class="copyText" laceholder="Phone"><br>
<input type="text" class="copyText" placeholder="E-Mail"><br>
<button>Copy</button>
Upvotes: 1
Reputation: 868
Use each()
function of jQuery
$('button').on('click', function () {
$(':input[type="text"]').each(function( index ){
$(this).select();
document.execCommand('copy');
alert('Text Copied');
});
});
Doc jQuery : https://api.jquery.com/each/
Upvotes: 0