체크박스(checkbox) 조회 및 설정 방법


<div class="chk_list">

<ul class="bg_chk54" id="prdList"> 

<li data-prd_id="0001" data-prd_nm="간장진미채">

   <input type="checkbox" id="chk01" name="chklist" class="bg">

   <label for="chk01">간장진미채</label>

</li>

<li data-prd_id="0002" data-prd_nm="오징어무침">

   <input type="checkbox" id="chk02" name="chklist" class="bg">

   <label for="chk02">오징어무침</label>

</li>

</ul>

</div>

1. 체크박스 설정

1) jQuery로 체크박스 설정

   $("#chk01").prop('checked', false) ; // 체크박스를 false로 설정

   $("#chk02").prop('checked', true) ;  // 체크박스를 true로 설정

   $("input[name=chklist]").prop('checked', true); // 모든 체크박스를 false로 설정

   $("input[name=chklist]").removeAttr("checked"); // 모든 체크박스를 false로 설정


2) 체크박스 직접 checked             

   <li>

      <input type="checkbox" id="chk01" name="chklist" class="bg" checked>

      <label for="chk01"><span></span>간장진미채</label>

   </li>


2. 체크박스 값 조회

1) 하나씩 조회

   var result = $("#chk01").prop('checked') ; // true, false

   var result = $("#chk01").is(":checked") ; // true, false

2) 전체 조회

   var checkedCount = 0;

   var checkedId = "";

   $('#prdList_no').find('li').each(function(index){

if($(this).children("input").is(":checked")){  // 또는 .prop("checked")

  checkedId += $(this).data('prd_id')+" ";

  checkedCount++;

}

   });

   alert("체크된 갯수:"+checkedCount+", 체크된 상품ID="+checkedId);


3. 클래스 토글, 추가, 삭제

   $('input[name=chklist]:checked').each(function() {

$(this).toggleClass("checksign", true); // addClass, removeClass

   });

+ Recent posts