-
checkbox의 상태에 대한 선택jQuery 2020. 12. 23. 18:55
checkbox의 상태가 checked인지 아닌지에 따라 선택하여 속성 변경해주기
취미 체크박스 생성
<label>hobby : </label>
<input type="checkbox" name="hobby" value="game" id="game">
<label for="game">game</label>
<input type="checkbox" name="hobby" value="movie" id="movie">
<label for="movie">movie</label>
<input type="checkbox" name="hobby" value="music" id="music">
<label for="music">music</label>
체크박스가 체크 되면 커지게 동작시켜보자
<script>
$(document).ready(function(){
// input 태그 중 체크 된 객체 선택
$("input:checked").css({"width":"50px","height":"50px"});
});
</script>
이렇게 수행해보려 했으나 동작하지 않았다
이유는 페이지가 로드 된 다음 수행되는 코드인데
페이지 로드 시(즉 페이지 켜졌을 시점)에는 체크 된 박스는 없기 때문에 수행되지 않는다
그렇다면
jQuery가 제공하는 change() 메소드 사용
input 태그의 checkbox에 변화가 있을 때 checkedChange 라는 함수를 동작시키겠다~
$("input:checkbox").change(checkedChange);
동작 시킬 checkedChange 함수 정의
function checkedChange(){
console.log($(this).prop("checked"));
// this -> 변화가 있었던 체크박스
// prop()메소드로 true or false인지 먼저 알아온 후 그 상태에 따른 조건문 작성
// 선택한 요소의 값이 'checked'일 경우 커지게 아닐경우 다시 작아지게
if($(this).prop("checked")){
$(this).css({"width":"50px","height":"50px"});
} else{
$(this).css({"width":"15px","height":"15px"});
}
}

change() 메소드 쓰고 얻은 왕왕체크박스 'jQuery' 카테고리의 다른 글
순서에 따른 필터 선택자(first,last,even,odd) (0) 2020.12.23 input 태그의 활성화,비활성화 상태에 따른 선택 (0) 2020.12.23 select > option 태그의 상태에 대한 선택(drop down list) (0) 2020.12.23 input태그의 type에 따른 객체 선택 (0) 2020.12.23 jQuery 개요 (0) 2020.12.23