Reputation: 323
I trying to copy to clipboard the values inside the input fields. The code to get these values is working fine, when I click on the button for "copy", with the alert() function as little debug, I can see the right value inside... but when I try to take this value to copy to clipboard, an error comes up. I have seen a lot of example around the web, but only for an element... So, this is my code that shows the right value, but not works for a copy.
$(document).ready(function() {
$('div#screen_wrap').each(function() {
var elem = $(this);
$("#copycoords", elem).click(function() {
var coords = $("#coords", elem).val();
coords.select(); // This line is the error
document.execCommand("copy", false);
alert(coords);
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="screen_wrap" class="glass">
<div><img src="img.jpg" /></div>
<p>Country 1</p>
<input type="text" value="47.529016,19.050963" id="coords" />
<input type="button" value="Copia" id="copycoords" class="btn1" />
</div>
<div id="screen_wrap" class="glass">
<div><img src="img.jpg" /></div>
<p>Country 2</p>
<input type="text" value="41.662055,-0.894292" id="coords" />
<input type="button" value="Copia" id="copycoords" class="btn1" />
</div>
<div id="screen_wrap" class="glass">
<div><img src="img.jpg" /></div>
<p>Country 3</p>
<input type="text" value="38.461808,27.217074" id="coords" />
<input type="button" value="Copia" id="copycoords" class="btn1" />
Upvotes: 2
Views: 4143
Reputation: 10237
Firstly, your id
attribute needs to be uniques across all dom elements. Secondly, the select()
needs to be on a dom element. You can modify the code as below.
$('input[type="button"]').click(function() {
$(this).parent().find('input[type="text"]').select();
document.execCommand("copy", false);
});
input {
outline: none;
}
input::selection {
color: initial;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="glass">
<div><img src="img.jpg" /></div>
<p>Country 1</p>
<input type="text" value="47.529016,19.050963" />
<input type="button" value="Copia" class="btn1" />
</div>
<div class="glass">
<div><img src="img.jpg" /></div>
<p>Country 2</p>
<input type="text" value="41.662055,-0.894292" />
<input type="button" value="Copia" class="btn1" />
</div>
<div class="glass">
<div><img src="img.jpg" /></div>
<p>Country 3</p>
<input type="text" value="38.461808,27.217074" />
<input type="button" value="Copia" class="btn1" />
</div>
Upvotes: 1
Reputation: 2815
You are using the select
function on the value of the element - $("#coords", elem).val();
, you should just call it on the element itself - $("#coords", elem).select()
Btw. $("#coords", elem)
is unnecessary, you shouldn't use the same id anywhere in the page as ids are supposed to be unique, so $("#coords")
should suffice
Upvotes: 2