JavaScript | JQuery

[JQuery] Checkbox에서 체크된 값 가져오기 | checkbox value 구하는법

엘라 ELLA 2023. 2. 8. 13:00
728x90
반응형

 

 

게시글이 도움이 되었다면

[로그인]이 필요 없는 ❤ 클릭과

게시글의 광고를 클릭 해 주세요:)

 

input checkbox 에서 체크된 값 console창에 띄우는 법

 

    $('input:checkbox[name={설정한 체크박스의 name}]').each(function () {
        if($(this).is(":checked")==true){
            console.log($(this).val());
        }
    })
}

 

 


 

활용 예시

Table checkbox에서 선택한 값들 가지고오기

 

[HTML코드]

<table class="table table-bordered text-center" id="Fruit">
                <tr>
                    <th scope="col">선택</th>
                    <th scope="col">이름</th>
                    <th scope="col">가격</th>
                </tr>
                </thead>
                <tbody class="align-middle">
                  <td class="text-center"><input name="checkedFruit" type="checkbox" value="apple"></td>
                  <td>사과</td>
                  <td>3,000</td>
                </tbody>
                <tbody class="align-middle">
                  <td class="text-center"><input name="checkedFruit" type="checkbox" value="banana"></td>
                  <td>바나나</td>
                  <td>2,000</td>
                </tbody>
                <tbody class="align-middle">
                  <td class="text-center"><input name="checkedFruit" type="checkbox" value="orange"></td>
                  <td>오렌지</td>
                  <td>1,500</td>
                </tbody>
            </table>

<button onclick="alert()"> 제출 </button>

 

 

[JQuery 코드]

function alert(){
    $('input:checkbox[name=checkedFruit]').each(function () {
        if($(this).is(":checked")==true){
        //console.log 등 다양하게 활용 가능
            alert($(this).val());
        }
    })
}

 

결과

*보고계신 코드펜에서는 alert기능이 정상적으로 작동하지 않을 수도 있습니다.

See the Pen jquery table checkbox value by Ella (@Ella_develop_floor) on CodePen.

 

 

 


 

게시글이 도움이 되었다면

[로그인]이 필요 없는 ❤ 눌러주세요:)

반응형