개발이야기/jQuery

[jQuery] input name 배열 값 가져오기, 유효성 검사

후린개발자 2023. 7. 3.
반응형

아래 소스 코드는 input name 배열의 값에 대해서 각각의 입력 필드에 대해 유효성을 검사하는 기능을 구현하고 있습니다.
each() 함수를 통해서 classe_cnt [], age_cnt [] 이름을 가진 입력 필드에 대해 반복적으로 코드가 실행됩니다.
index 매개 변수를 통해서 입력 필드 값이 비어 있으면 메시지를 보여 줍니다.

간단한 소스 코드이니 응용해서 사용하시면 됩니다.

 

<script type="text/javascript" src="https://code.jquery.com/jquery-1.10.2.min.js" /></script>
<script>
$(function() {
	$("#btn_check").click(function(){
		$("input[name='classe_cnt[]']").each(function(index) {
			var classeCntValue = $(this).val();
			if (classeCntValue == "") {
				alert("학번: " + (index + 1) + " 입력 해주세요.");
			}
		});	
		$("input[name='age_cnt[]']").each(function(index) {
			var ageCntValue = $(this).val();
			if (ageCntValue == "") {
				alert("나이: " + (index + 1) + " 입력 해주세요.");
			}
		});	
	});
});
</script>
<div>
	<button type="button" id="btn_check"><strong>확인</strong></button>
</div>
<table class="table table-bordered table-striped" id="tb">
	<thead>
		<tr>
			<th style="text-align:center;vertical-align:middle;">No</th>
			<th style="width:110px;text-align:center;vertical-align:middle;">학번</th>
			<th style="width:110px;text-align:center;vertical-align:middle;">나이</th>
		</tr>
	</thead>
	<tbody id="tbody_id">
		<tr>
			<td class="text-center">1</td>
			<td class="text-center"><input type="text" class="form-control input-sm" name="classe_cnt[]" onkeyup="this.value=this.value.replace(/[^0-9]/g,'');"></td>
			<td class="text-center"><input type="text" class="form-control input-sm" name="age_cnt[]"   onkeyup="this.value=this.value.replace(/[^0-9]/g,'');"></td>		
		</tr>
		<tr>
			<td class="text-center">2</td>
			<td class="text-center"><input type="text" class="form-control input-sm" name="classe_cnt[]" onkeyup="this.value=this.value.replace(/[^0-9]/g,'');"></td>
			<td class="text-center"><input type="text" class="form-control input-sm" name="age_cnt[]"   onkeyup="this.value=this.value.replace(/[^0-9]/g,'');"></td>
		</tr>
		<tr>
			<td class="text-center">3</td>
			<td class="text-center"><input type="text" class="form-control input-sm" name="classe_cnt[]" onkeyup="this.value=this.value.replace(/[^0-9]/g,'');"></td>
			<td class="text-center"><input type="text" class="form-control input-sm" name="age_cnt[]"   onkeyup="this.value=this.value.replace(/[^0-9]/g,'');"></td>
		</tr>
	</tbody>
</table>
반응형

댓글

💲 추천 글