WEB/JavaScript

[JavaScript][event handler 활용] 2. 사용자의 입력 값을 실시간으로 출력하기

bay07 2024. 4. 22. 17:25

▶ input 이벤트 실습 

사용자의 입력 값을 실시간으로 출력하기 

 


더보기
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <input type="text" id="text-input">
  <p></p>

  <script>
    // 1. input 태그 선택
    const inputTag = document.querySelector('#text-input')

    // 3.2 p 태그 선택
    const pTag = document.querySelector('p')

    // 2. 콜백 함수 (input 태그에 input 이벤트가 발생할때마다 실행되는 코드)
    const inputHandler = function (event) {
      // 3.1 사용자가 입력한 데이터가 어디에 있는지 찾기
      // console.log(event)
      // console.log(event.currentTarget.value)
      // console.log(this.value)

      // 3.3 사용자 입력 데이터를 p 태그의 컨텐츠로 저장
      pTag.textContent = event.currentTarget.value
    }

    // 4. 선택한 input 태그에 이벤트 핸들러 부착
    inputTag.addEventListener('input', inputHandler)
  </script>
</body>


</html>

 출력