Home > Software design >  Copying the contents of multiple inputs to the clipboard
Copying the contents of multiple inputs to the clipboard

Time:11-14

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');
    });
});

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related