<input type="text" name="" id="">
<textarea name="" id="" cols="30" rows="10"></textarea>
두가지 방법이 있다
input 태그는 한 줄 입력이 가능하다
textarea 태그는 여러 줄 입력이 가능하다.
두가지 속성안의 값을 가져올 때는 value 를 사용하고 자주 사용하는 이벤트로는
change, keydown, keyup, keypress 이벤트가 주로 사용된다
inch를 입력받은 후 cm단위로 변환하여 출력하자
<!DOCTYPE html>
<html lang="en">
<head>
<script>
document.addEventListener('DOMContentLoaded', () => {
const input = document.querySelector('input')
const button = document.querySelector('button')
const p = document.querySelector('p')
button.addEventListener('click', () => {
p.textContent = `${Number(input.value) * 2.54}cm로 변환하였습니다.`
})
})
</script>
</head>
<body>
<input type="text" name="" id=""> inch<br>
<button>계산</button>
<p></p>
</body>
</html>
input 태그로 입력을 받을 수 있도록 만들었다
이후 버튼이 눌렸을 때 input 태그 안의 값에 2.54를 곱하여 cm단위로 만든 후
자료형을 숫자로 변환한 뒤 p태그에 넣는 코드이다
버튼을 누르지 않아도 곧바로 단위 변환이 되도록 만들어보자
<!DOCTYPE html>
<html lang="en">
<head>
<script>
document.addEventListener('DOMContentLoaded', () => {
const input = document.querySelector('input')
const p = document.querySelector('p')
input.addEventListener('keyup', () => {
p.textContent = `${Number(input.value) * 2.54}cm로 변환하였습니다.`
})
})
</script>
</head>
<body>
<input type="text" name="" id=""> inch<br>
<p></p>
</body>
</html>
버튼의 click 이벤트가 아닌 input 태그에서 keyup 이벤트를 활용하면 즉각적으로 단위 변환이 일어난다
keydown, keypress 이벤트를 써도 같은 결과가 나오지 않을까?
아니다. 이벤트가 일어나는 순서를 알게되면 이해가 된다
keydown -> keypress -> 값이 들어감 -> key up
위와 같은 순서로 진행되기 때문에 keydown, keypress 일때는 아직 값이 들어가지 않은것이다
입력 양식 전체에 값 입력을 마쳤을 때 이벤트가 발생한다
간단하게 말하면 입력하는 곳에 원하는 값을 입력한 후 엔터를 누르면 발생하는 것이다
마우스로 입력 칸이 아닌 다른 곳을 클릭하는 경우에도 발생한다