3

I want to copy the input value when I click the div, but I can't get it to work. Here is my code:

function handleClick() {
    input.select();
    document.execCommand("copy");
}
#input {
  display: none
}
<div click="handleClick()">
  <input type="text" value="test" id="input">
</div>    

When I remove the css style of display: none, it works.

Why can't I hide the input element? I just want to use input's .select(), but don't want input show in my page, how can I do this?

Calvin Nunes
  • 6,376
  • 4
  • 20
  • 48
Zuckjet
  • 807
  • 1
  • 10
  • 19
  • You can hide the input with position absolute or visibility + overflow hidden and other methods, you don't have to use display none – Huangism Aug 02 '18 at 13:05
  • 2
    `select()` does not work on a hidden element. When you want to set something in the clipboard, the usual approach is to display the input where the user cannot see it, and remove it after clipboard is loaded. – sjahan Aug 02 '18 at 13:06
  • I also try visibility:hidden, it cannot work too. Maybe overflow hidden is a solution, but I want to know why my code not work ,and is there any documentation describe this? – Zuckjet Aug 02 '18 at 13:09
  • thanks for your reply, can you show me any document about this ? I found nothing about it on MDN.@sjahan – Zuckjet Aug 02 '18 at 13:11
  • 1
    This [answer](https://stackoverflow.com/a/31596687/9208870) could help you, and can keep the input's display property set to none. – Z.Dima Aug 02 '18 at 13:49

2 Answers2

3

You can use opacity... instead of visibility (but the element will be there ocupping space...) or you can use position: absolute + top: -100px for example.

function handleClick() {
  var input = document.getElementById("input");
  //var input = document.getElementById("input2"); //Use this class to test with other possibility 
  input.focus();
  input.select();
  var copy = document.execCommand("copy");    
  console.log("copied");
}
#input {
  opacity: 0
}

/* Use this class to test with other possibility */
#input2{
  position: absolute;
  top: -100px;
}

#clicker{
  width: 250px;
  height: 75px;
  border: 1px solid;
}
<div id='clicker' onclick="handleClick()">
  <input type="text" value="test" id="input">
</div>
<br>
<input placeholder="Click DIV then PASTE here..."/>
Calvin Nunes
  • 6,376
  • 4
  • 20
  • 48
0

Correct me if i'm wrong. your goal is to hide the input tag right?

Then why not use this?

<input type="hidden" id="custId" name="custId" value="3487">

then change the div to

<div onclick="handleClick()">