Sergey Pervushin
Sergey Pervushin

Reputation: 363

Copying the contents of multiple inputs to the clipboard

I have some fields with some text. Each field has its own button for copying to the clipboard. But I can't get it to work correctly in any way.

The structure is as follows

<div class="field">
    <input type="text" value="some text" />
    <span class="copy">Copy!</span>
</div>
<div class="field">
    <input type="text" value="some text2" />
    <span class="copy">Copy!</span>
</div>
<div class="field">
    <input type="text" value="some text3" />
    <span class="copy">Copy!</span>
</div>

The following code works if there is one field, but what if there are several.

$('.field').on('click', '.copy', function () {
    var copyText = $('.field input');
    copyText.select();
    document.execCommand('copy');
});

I probably need something like each and closest, but I can't figure out how to apply it(

$('.field').each(function () {
    var copyText = $('.field input');
    $(this).on('click', '.copy', function () {
        copyText.select();
        document.execCommand('copy');
    });
});

Upvotes: 0

Views: 420

Answers (1)

SKJ
SKJ

Reputation: 2326

You need to use $(this) and prevAll()

https://api.jquery.com/prevall/

$('.field').on('click', '.copy', function () {
    var copyText = $(this).prevAll("input"); 
    var copyTextVal = $(copyText).val();
    $(copyText).select();
    document.execCommand('copy');
    
    // debug infos 
    console.clear();
    console.log(copyTextVal);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="field">
    <input type="text" value="some text" />
    <span class="copy">Copy!</span>
</div>
<div class="field">
    <input type="text" value="some text2" />
    <span class="copy">Copy!</span>
</div>
<div class="field">
    <input type="text" value="some text3" />
    <span class="copy">Copy!</span>
</div>

Upvotes: 1

Related Questions