해제 가능한 라디오 버튼 unchecked radiobutton > 그누보드5 팁자료실

그누보드5 팁자료실

해제 가능한 라디오 버튼 unchecked radiobutton 정보

해제 가능한 라디오 버튼 unchecked radiobutton

본문

그룹에서 값을 1개만 선택해야 하는 경우에 type=radio 를 많이 씁니다.

그런데 checkbox와 다르게 radio 타입은 해제가 되지 않습니다.

선택안함이라는 체크박스를 하나 더 넣어도 되지만, 이게  직관적이 않습니다.

"선택안함을 선택함" <-- 좀 이상하죠.

 

그래서 해제가 가능한 radio를 만들어봤습니다. 유용하게 쓰실곳이 있을겁니다.


<ul>
    <li><input type='radio' name='radioBtn'>체크1</li>
    <li><input type='radio' name='radioBtn'>체크2</li>
    <li><input type='radio' name='radioBtn'>체크3</li>
</ul>
 
<script>
$(document).on("click", "input[name='radioBtn']", function(){
    thisRadio = $(this);
    if (thisRadio.hasClass("imChecked")) {
        thisRadio.removeClass("imChecked");
        thisRadio.prop('checked', false);
    } else { 
        thisRadio.prop('checked', true);
        thisRadio.addClass("imChecked");
    };
})
</script>

jsfiddle 은 이쪽 링크

https://jsfiddle.net/6vn5uo0t/1/

 

 

추천
7
  • 복사

댓글 7개

팁 감사합니다!
스크립트 부분을 약간 수정해봤습니다

$(document).on("click", "input[name='radioBtn']", function(){
    thisRadio = $(this);
    if (thisRadio.hasClass("imChecked")) {
        thisRadio.prop('checked', false).removeClass("imChecked");
    } else {
        thisRadio.prop('checked', true);
        thisRadio.parent().siblings().find("input[name='radioBtn']").prop('checked', false);
        thisRadio.addClass("imChecked").parent().siblings().find("input[name='radioBtn']").removeClass("imChecked");     
    };
})
© SIRSOFT
현재 페이지 제일 처음으로