0

Can anyone tell me how do you clone from a span element and append to input value by clicking the span element itself? Here is the script.

<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script>
    $(document).ready(function() {
      $("span#username").click(function() {
        $("span#username").clone().appendTo("#test");


      });
    });
  </script>
</head>

<body>

  <span id="username"> User </span><br><br>
  <input type="text" id="test" value="" />


</body>

</html>

1 Answer 1

1

You have to set the value of the input (jQuery.val()) to the text content of the span (jQuery.text()) like this:

// IDs are enough
$("#username").click(function() {
    $("#test").val($(this).text()); // this is the span beign clicked
});

No jQuery:

document.getElementById("username").addEventListener("click", function() {
    document.getElementById("test").value = this.textContent;
});
Sign up to request clarification or add additional context in comments.

1 Comment

@Neof I added the code with no jQuery, just vanilla JS!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.