본문 바로가기
개발노트

소수점 1개만 입력 가능하도록

by SoonNote 2022. 4. 29.
반응형

달러를 입력받는 경우가 있었는데 소수점이 여러개 찍히는 경우가 생겼다.

 

스크립트를 통해 2개이상 입력시 지우는 방식과 0~9숫자와 소수점만 입력가능하도록 한다.



<input  type="text" name="price" id="price"  value="${test.test}"  maxlength="12" class="w20" />

<script>
	$("#price").each(function() {
		$(this).keyup(function() {
			if ($(this).val() != null && $(this).val() != '') {
				var tmps = $(this).val().replace(/[^\.0-9\.]/g, '');
				/* 소수점은 하나만 입력되도록*/
				var arr = tmps.split(".");
				if (arr.length > 2) {
					tmps = arr[0] + '.' + arr[1];
				}
				$(this).val(tmps);
			}
		});
		$(this).focusout(function() {
			if ($(this).val() != null && $(this).val() != '') {
				var tmps = $(this).val().replace(/[^\.0-9\.]/g, '');

				/* 소수점은 하나만 입력되도록*/
				var arr = tmps.split(".");
				if (arr.length > 2) {
					tmps = arr[0] + '.' + arr[1];
				}
				$(this).val(tmps);
			}
		});
	});
</script>
반응형