개발이야기/jQuery

[jQuery] form 초기화(리셋) 사용법 (form clearForm)

후린개발자 2022. 11. 22.
반응형

jquery로 간단히 form을 리셋시키는 간단한 메서드를 알려 드립니다.
jquery 객체에 사용자 메서드를 추가해서 $("셀렉터") 부분에 form id를 지정하시면 됩니다.

저는 초기화 버튼을 클릭하면 메서드를 호출해 form을 리셋시키는 구조입니다.
간단한 소스이니 금방 사용 가능하실 것 같습니다.

 

소스코드

<link rel="stylesheet" type="text/css" media="screen" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(document).ready(function() {  
	$.fn.clearForm = function(){
		var tabindex = 1;
		$(this).each(function(){
			this.reset();
		});
		$(this).find('input,select').each(function(){
			if (this.type != "hidden") {
				$(this).attr("tabindex", tabindex);
				tabindex++;
			}
		});
	}

	$("#btn_reset").click(function(){
		$("#frm_user_info").clearForm();
	});
});
</script>
<form class="form-horizontal" id="frm_user_info" name="frm_user_info" onsubmit="return false;">
	<fieldset style="padding-top:50px;">
		<div class="form-group">
			<label class="col-md-1 control-label">이름</label>
			<div class="col-md-4">
				<input type="text" class="form-control input-sm" name="user_name" >
			</div>
			<label class="col-md-1 control-label">휴대전화번호</label>
			<div class="col-md-4">
				<input type="text" class="form-control input-sm"  name="phone" >
			</div>
		</div>
		<div class="form-group">
			<label class="col-md-1 control-label">성별</label>
			<div class="col-md-4">
				<select class="form-control input-sm" name="gender"  >
					<option></option>
					<option value="M">남성</option>
					<option value="F">여성</option>
				</select>
			</div>
			<label class="col-md-1 control-label">별명</label>
			<div class="col-md-4">
				<input type="text" class="form-control input-sm"  name="nick" >
			</div>
		</div>
		<div class="form-group">
			<label class="col-md-1 control-label">자기소개</label>
			<div class="col-md-10">
				<textarea name="cnts" rows="7" class="form-control input-sm" style="resize:none;"></textarea>
			</div>
		</div>
		<div class="form-actions" style="float:right; padding-right:120px;">
			<button type="button" class="btn btn-info btn-sm" id="btn_reset">
				<strong>초기화</strong>
			</button>
		</div>
	</fieldset>
</form>

 

 

소스화면

소스화면

 

반응형

댓글

💲 추천 글