[JS] selector 클릭시 class 추가/삭제 (button 타입)

Sora Kim·2022년 11월 24일
0

JS / jquery

목록 보기
11/12

예시화면

html

<button type="button" id="1" class="notiTypeBtnAll" onclick="" title="">전체(All)</button>
<button type="button" id="10" class="notiTypeBtn" onclick="" title="">신규(New)</button>
<button type="button" id="20" class="notiTypeBtn bt-checked" onclick="" title="">부록(Add)</button>
<button type="button" id="30" class="notiTypeBtn bt-checked" onclick="" title="">개정(Rev)</button>
<button type="button" id="40" class="notiTypeBtn" onclick="" title="">수정(Corr)</button>
<button type="button" id="50" class="notiTypeBtn" onclick="" title="">보충(Supp)</button>

<input type="hidden" id="notiType" name="notiType">

js

class명 bt-checked를 넣어주면 빨간색박스로 변경

// 신규, 부록, 개정, 수정, 보충 버튼 클릭시 (전체버튼을 제외한 버튼)
$(".notiTypeBtn").on("click",function(){
  //클릭한 버튼이 클릭되어있으면 bt-checked class 제거, 아니였으면 bt-checked class 추가
  $(this).toggleClass('bt-checked');
  	/*  toggleClass를 사용하면 if-else로 hasClass, removeClass 기능을 구현하는 거 와 같은 기능으로 사용가능 .
    	// hasClass, removeClass 를 if-else로 구분지어 사용했을 시, 
    	if($(this).hasClass('bt-checked')){
			$(this).removeClass('bt-checked');
		} else {
			$(this).addClass('bt-checked');
		} */
  
  // 전체버튼에 체크 되어있었을 시, 해제
  $(".notiTypeBtnAll").removeClass('bt-checked');
	
  
  let notiArr = [];
  // 선택된 button id 값 notiArr 배열에 넣기
  $.each($(".bt-checked"), function(index, value){
    notiArr.push(value.id);
  })
  
  console.log("active btn id =",notiArr);
  
  // 전부다 체크되어있을시에는 전체 버튼에 class 추가
  if(notiArr.length == 5){ 
    console.log("전체체크");
    $(".notiTypeBtnAll").addClass('bt-checked');
    $(".notiTypeBtn").removeClass('bt-checked');
  }
  
  $("#notiType").val(notiArr);
});

// all 전체 클릭시
$(".notiTypeBtnAll").on("click",function(){
  $(this).toggleClass('bt-checked');
  $(".notiTypeBtn").removeClass('bt-checked');
  let notiArr = ['10','20','30','40','50'];
  $("#notiType").val(notiArr);
});

console.log

참고

toggleClass()관련

https://api.jquery.com/toggleclass/

profile
개발잘하고시풔!!!!!!!

0개의 댓글