HTML / input / number / 숫자 입력하는 양식
목차
input type="number"
input 태그의 type을 number로 하면 숫자만 입력할 수 있다.
<!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <title>JavaScript</title> <style> * { font-family: Consolas, monospace; font-size: 24px; } </style> </head> <body> <form method="get" action=""> <p><input type="number" name="number" placeholder="Input number"></p> <p><input type="submit" value="Submit"></p> </form> </body> </html>
외관 상으로는 차이가 없으나...
숫자 이외의 것을 입력하고 전송하려 하면 경고 메시지가 나오고 전송되지 않는다.
소수도 입력 가능하게 하기
별도의 설정을 하지 않으면 소수를 전송할 수 없다.
소수를 입력 받고 싶다면 step 속성을 추가한다. 예를 들어 step의 값을 0.01로 하면 소수 둘째 자리까지 입력 가능하다.
<input type="number" name="number" step="0.01" placeholder="Input number">
화살표로 값을 변경할 때도 0.01 단위로 조정된다.
사용할 일이 많을지는 모르겠으나, 3의 배수를 입력 받고 싶다면 step의 값을 3으로 정한다.
<input type="number" name="number" step="3" placeholder="Input number">