교수님, 체크박스 질문있어요,,.엉엉
본문
다음과 같은 질문을 해서 조교님이 알려주셨는데...
제가 오로지 짜집기 출신이라 해결이 안되네요...
요즘 강의땜에 시간도 없으시거 귀찮으시겠지만 코드를 어떻게 해야 할지 알려주시면 고맙겠습니다,,
올해는 이거 꼭 해결해야 하는데..엉엉
나의 질문:
체크박스 선택갯수 3개까지 제한해서 글쓸때는 잘되는데요,,
문제는 글을 쓰고 수정할 때 또다시 선택할 수 있네요..
최초 저장할때 3개까지 체크되어 글을 썼는데 다시 수정하면 또 3개를 선택할 수 있어서 제한이 의미가 없어집니다.
이런 경우 어떻게 해야 할까요?
소스는 이렇습니다.
<script language=javascript>
var maxChecked = 3; //선택가능 갯수
var totalChecked = 0; // 설정 끝
function CountChecked(field) {
if (field.checked) totalChecked += 1;
else totalChecked -= 1;
if (totalChecked > maxChecked) { alert ("최대 3개 까지만 가능합니다.");
field.checked = false; totalChecked -= 1;
}
}
function ResetCount(){ totalChecked = 0;}
</script>
<input type="checkbox" onclick=CountChecked(this) id="ext18_00" name="ext18_00" value="1번" <? if($ext18_00 == "1번") echo 'checked="checked"'; ?>>
<label for="ext18_00">01번</label>
<input type="checkbox" onclick=CountChecked(this) id="ext18_01" name="ext18_01" value="2번" <? if($ext18_01 == "2번") echo 'checked="checked"'; ?>>
<label for="ext18_01">02번</label>
<input type="checkbox" onclick=CountChecked(this) id="ext18_02" name="ext18_02" value="3번" <? if($ext18_02 == "3번") echo 'checked="checked"'; ?>>
<label for="ext18_02">03번</label>
<input type="checkbox" onclick=CountChecked(this) id="ext18_03" name="ext18_03" value="4번" <? if($ext18_03 == "4번") echo 'checked="checked"'; ?>>
<label for="ext18_03">04번</label>
<input type="checkbox" onclick=CountChecked(this) id="ext18_04" name="ext18_04" value="5번" <? if($ext18_04 == "5번") echo 'checked="checked"'; ?>>
<label for="ext18_04">05번</label>
조교님 답변:
수정시엔 저장된 값을 불러와서 totalChecked 값을 설정해주고
저장할때 무조건 기존값을 지우고 업데이트 치는 식으로 설정해주시면 되겠네요.
근본적으로는 jquery 등을 사용해서 onload 타임에 값을 체크하고, onchange 마다 전체 선택값의 카운트를 세는 방식으로 처리하는 것이 좋을것 같습니다.
답변 2
id="ext18_00", id="ext18_01" ~~~ --> class='ext18'로 모두 바꾸세요
onclick=CountChecked(this) 모두삭제하세요
자바스크립트 몽땅 삭제 하고 아래처럼 바꾸세요
<script>
$(function(){
$('.ext18').click(function(){
if($(".ext18:checked").length >3){ alert('3개까지만'); $(this).attr("checked",false); }
});
});
</script>
window.onload = function() {
for (var i=0; i<5; i++)
if (document.getElementById('ext18_0' + i).checked == true)
++totalChecked;
}