개발/JavaScript

javascirpt | input 여러개 숫자만 입력가능하도록 설정 | input only text getElementsByClassName

AM0530 2021. 9. 17. 13:53

jsp에 input이 forEach 문으로 여러개 만들어지고, 

해당 input에 모두 숫자만 입력하게 하고 싶을 때 

 

HTML

<c:forEach var="test_var" items="${list}" varStatus="vs">
	<input type="text" id="a_${vs.count}" class="test_class" name="b_${vs.count}" value=""> 단위
</c:forEach>

 

JavaScript

<script>
var elements = document.getElementsByClassName("test_class");

function update() {
	var value = this.value;
	var id = this.id; 
	
	value = value.replace(/[^0-9]+/g,'');
	if(id != '' || id != null){
		document.getElementById('' + id + '').value = value;
	}			
}

Array.from(elements).forEach(function(element) {
	element.addEventListener('input', update);
});
</script>

 

* 참고 

https://stackoverflow.com/questions/19655189/javascript-click-event-listener-on-class

 

JavaScript click event listener on class

I'm currently trying to write some JavaScript to get the attribute of the class that has been clicked. I know that to do this the correct way, I should use an event listener. My code is as follows...

stackoverflow.com