logo

An example of inputting a string in a text form by clicking in JavaScript 📂Programing

An example of inputting a string in a text form by clicking in JavaScript

Showcase

LongText
RecentlyUsed

In the example above, clicking “LongText” or “RecentlyUsed” appends that string to the input field. This feature is especially useful when allowing users to conveniently insert frequently used text or special characters. There is no particular reason for the specific strings, so once you understand the principle you can apply it to a variety of features.

코드

HTML

<div class="pick">LongText</div>
<div class="pick">RecentlyUsed</div>

<input type="text" id="prompt">
  • class="pick": denotes a clickable element.
  • id="prompt": designates the input field that will receive the text.

javascript

<script>
  document.querySelectorAll(".pick").forEach(element => {
    element.addEventListener("click", function() {
      const inputValue = this.textContent; // 클릭된 요소의 텍스트 가져오기
      document.getElementById("prompt").value += inputValue;
    });
  });
</script>
  • querySelectorAll(".pick"): targets elements whose class is “pick”.
  • addEventListener("click", ...): specifies the function to execute when a click event occurs.
  • inputValue = this.textContent: retrieves the inner text of the clicked element. Because it’s the content itself rather than an attribute, it’s straightforward to present to users.
  • getElementById("prompt").value += inputValue: appends the clicked element’s inner text to the input field.