How do I copy/select a var in jquery?

Asked

Viewed 39 times

1

I’m trying to copy the contents of var ip, but I can’t.

This is my code:

  $(function(){
    $("#ip-server").click(function(){
      var ip = 'ip.exemplo.com'; /* <-- Esse é o conteudo que quero copiar */
      $('ip').select();
      document.execCommand('copy');
    })
  })
  • Voce wants to take the value of a field with $('ip').select(); and assign using the other using $("#ip-server").prop(...)?

  • No, I just want to copy the var ip for the user’s client client.

1 answer

0

How you need to copy the variable value ip for the user’s Clipboard, I imagine you will need an element to access the value by jQuery:

$("#ip-server").click(function () {
  var ip = 'ip...';
  var $temp = $("<input>"); // cria um elemento temporário
  $("body").append($temp); // insere ele no DOM
  $temp.val(ip); // atribui o valor do IP que deseja a ele
  $temp.select(); // selecione para executar o comando
  document.execCommand("copy"); // copia para o clipboard
  $temp.remove(); // remove o elemento temporário da página
});

If the element $("#ipserver") contains the value you want, you can use the $(this).select() inside the function click above instead of creating a temporary element and removing it later. This will cause jQuery to redeem the value of the current element that received the event.

It is worth noting that the way you are rescuing the element:

$('ip')...

Would indicate an HTML tag of type ip. If you want to redeem from a class, use the prefix .:

$('.ip')...

And for Ids:

$('#ip')...

There are more advanced ways to access elements within other elements, I recommend researching if you are interested.

I hope I’ve helped in some way.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.