728x90
728x90
숫자를 소수점 8자리만 입력이 가능하게 하고 싶었다.
<input type="text" placeholder="0" id="i_number" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');"/>
type을 number를 사용할려고 했으나 소수점 입력시 커서가 앞으로 가고 값 입력하는게 이상했다.
type="text"를 사용하였고
oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');"
oninput 이벤트를 사용해서 숫자만 인력가능하게 하였다.
[ 내가 원하는 함수 ]
1. 소수점은 8자리까지 입력가능
2. 맨 앞 00 연속으로 입력되는걸 막기
3. 맨 앞이 0이고 뒤에 소수점이 오지않을 때 0을 지우고 입력한 값을 넣어줌
$('#i_number').on("input propertychange paste change keyup focusout focusin keydown keypress", function (e) {
let inputValue = $(this).val();
// 소수점이 있는지 확인
if (inputValue.indexOf(".") !== -1) {
// 소수점 8자리까지만 입력했는지 검사
let regExp = /^\d*.?\d{0,8}$/;
if(!regExp.test(this.value)){
// 8자리 초과시 지움
$(this).val(inputValue.substring(0,inputValue.length-1));
} else {
$(this).val(inputValue);
}
} else {
if (inputValue.length >= 2 && inputValue[0] === '0') {
// 맨앞에 숫자가 연속으로 00이 오는걸 막음
if (inputValue[1] === '0') {
inputValue = inputValue.slice(1);
} else {
// 맨앞 숫자가 0일시 그 뒷숫자로 변경
inputValue = inputValue[1];
}
}
$(this).val(inputValue);
}
});
만들다보니 코드가 길어졌다...😒
더 간단한 방법이나 함수가 있다면 공유 부탁드립니다..
추가적으로 콤마까지 넣어줄 예정
728x90
728x90
댓글