테스트 사이트 - 개발 중인 베타 버전입니다

체크박스 및 라디오버튼 필수선택 함수

input 의 type 이 체크박스나 라디오버튼일 경우 하나 이상을 필수로 선택시키는 옵션이

은근히 까다로울 수 있어서 함수를 하나 만들어 보았습니다.

상단이나 하단에 자바스크립트 함수를 하나 선언합니다.

[code]

<script>
function trueCheck(...ipt) {
    count = 0;
    for (all of window[ipt[0]].querySelectorAll("input[type = " + ipt[1] + "]")) count += all.checked;
    if (count == 0) alert("하나이상 필수선택");
}
</script>

[/code]

 

----------

 

input 바깥에 span 을 하나 감고 그 span 에 id 를 하나 줍니다.

submit 버튼에 onclick="('span아이디','input타입')" 명령을 넣어 줍니다. "땡"

name 이 같아도 달라도 상관없고 name 꼬랑지에 [] 배열대괄호가 붙거나 말거나 상관 없습니다. 

 

<form id=firstForm>
    <span id=checkSpan>
        <input type=checkbox name=my value="체크하나">체크하나
        <input type=checkbox name=my value="체크둘">체크둘
        <input type=checkbox name=my value="체크셋">체크셋
    </span>
    <button type=input onclick="trueCheck('checkSpan','checkbox')">클릭</button>
</form>

<form id=secondForm>
    <span id=radioSpan>
        <input type=radio name=korea value="라디오하나">라디오하나
        <input type=radio name=china[] value="라디오둘">라디오둘
        <input type=radio name=japan value="라디오셋">라디오셋
    </span>
    <button type=input onclick="trueCheck('radioSpan','radio')">클릭</button>
</form>

 

----------

 

다음은 하나의 폼과 하나의 span 안에서의 예제입니다.

 

<form id=myForm>
    <span id=mySpan>
        <input type=checkbox name=my value="체크하나">체크하나
        <input type=checkbox name=my value="체크둘">체크둘
        <input type=checkbox name=my value="체크셋">체크셋
        <br>
        <input type=radio name=korea value="라디오하나">라디오하나
        <input type=radio name=china[] value="라디오둘">라디오둘
        <input type=radio name=japan value="라디오셋">라디오셋
    </span>
    <button type=input onclick="trueCheck('mySpan','checkbox');trueCheck('mySpan','radio')">클릭</button>
</form>

 

----------

 

span 을 없애고 아래처럼 쓰는 것이 어쩌면 더 간명합니다.

 

<form id=myForm>
    <input type=checkbox name=my value="체크하나">체크하나
    <input type=checkbox name=my value="체크둘">체크둘
    <input type=checkbox name=my value="체크셋">체크셋
    <br>
    <input type=radio name=korea value="라디오하나">라디오하나
    <input type=radio name=china[] value="라디오둘">라디오둘
    <input type=radio name=japan value="라디오셋">라디오셋
    <button type=input onclick="trueCheck('myForm','checkbox');trueCheck('myForm','radio')">클릭</button>
</form>

 

----------

 

그러니까 input 를 둘러싸고 있는 상위 엘레먼트의 id 와 input 의 type 를 가지고 함수를 만든 것이니

폼에 직접 또는 상황에 따라 span 을 감거나 하면 되겠습니다.

댓글 작성

댓글을 작성하시려면 로그인이 필요합니다.

로그인하기

댓글 6개

감사합니다. 요즘 그누보드에 빠져 있는데요, 비타주리님의 활동에 감탄만 하고 있습니다.
@김창헌 감사합니다
감사합니다.. 복 받으실겁니다..^^
@모차마 어이쿠 감사합니다.
좋은 팁 감사합니다.
@들레아빠 감사합니다.

게시판 목록

그누보드5 팁자료실

글쓰기