본문 바로가기
jQuery

jQuery로 html select에 readonly 효과 주기

by Dokon Jang 2021. 7. 29.
반응형

html select 태그에 readonly는 적용되지 않지만 늘 readonly 속성을 주고 제대로 작동 안해서 구글링을 합니다.

 

select에 readonly 효과 주기 위해서는 disabled 속성을 넣어주어야 합니다.

<select id="lang" disabled>
	<option value=""></option>
	<option value="JAVA">Java</option>
	<option value="C++">C++</option>
	<option value="C#">C#</option>
</select>

 

동적으로 사용/미사용을 해야 하는데 jQuery를 이용한 코드는 아래와 같습니다.

 

disabled 속성을 제거하면 사용 할 수 있습니다.

$("#lang").removeAttr("disabled");

 

disabled 속성을 넣으면 사용 할 수 없습니다.

$("#lang").attr("disabled","disabled");

 

전체 소스

<html>

<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	
	<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
	
	<script>
		
		function enableSelect(){
			$("#lang").removeAttr("disabled");
		}
		
		function disableSelect(){
			$("#lang").attr("disabled","disabled");
		}
		
	</script>
</head>

<body>
	<select id="lang" disabled>
		<option value=""></option>
		<option value="JAVA">Java</option>
		<option value="C++">C++</option>
		<option value="C#">C#</option>
	</select>
	
	<p>
	<input type="button" value="사용" onClick="enableSelect()"/>
	
	<p>
	<input type="button" value="미사용"  onClick="disableSelect()"/>
</body>
</html>
반응형

댓글