같은 name을 가지는 체크박스들 중 2개 이상이 선택되지 못하도록 만들기 위해 작성했던 스크립트인데, 혹시 필요하신 분이 있으실까 해서 올려봅니다.
function remain_two_obj(prefix){ this.old = new Array(); this.prefix = prefix; this.remain_two = function(cur){ items = document.getElementsByName(this.prefix + '[]'); for( i = 0, count = 0 ; i < items.length; i++ ) if( items[i].checked ) count++; if( count > 0 && cur.checked == false && this.old[0] == cur.value ) this.old[0] = this.old[1]; if( cur.checked == false ) return; if( count < 2 ) this.old[count] = cur.value; else { this.old[0] = this.old[1]; this.old[1] = cur.value; items = document.getElementsByName(this.prefix + '[]'); for( j = 0 ; j < items.length ; j++ ){ if( items[j].value != this.old[0] && items[j].value != this.old[1] ) items[j].checked = false; } } } } var cbox = new remain_two_obj('cbox'); |
필요한 개수만큼 remain_two_obj 를 선언하고 name prefix를 등록해주면 됩니다. 그런 체크 박스들에 onclick 이벤트를 등록해주면 끝!
<ul> <li><label><input type="checkbox" name="cbox[]" value="0" onclick="cbox.remain_two(this)" /> 0</label></li> <li><label><input type="checkbox" name="cbox[]" value="1" onclick="cbox.remain_two(this)" /> 1</label></li> <li><label><input type="checkbox" name="cbox[]" value="2" onclick="cbox.remain_two(this)" /> 2</label></li> <li><label><input type="checkbox" name="cbox[]" value="3" onclick="cbox.remain_two(this)" /> 3</label></li> <li><label><input type="checkbox" name="cbox[]" value="4" onclick="cbox.remain_two(this)" /> 4</label></li> <li><label><input type="checkbox" name="cbox[]" value="5" onclick="cbox.remain_two(this)" /> 5</label></li> <li><label><input type="checkbox" name="cbox[]" value="6" onclick="cbox.remain_two(this)" /> 6<label></li> <li><label><input type="checkbox" name="cbox[]" value="7" onclick="cbox.remain_two(this)" /> 7</label></li> </ul> |
쓰기 편하게 만드려고, class 화 해봤는데 참 개념이 독특하네요 자바스크립트는 -_-! function 으로 object를 만들어야 한다니…
This entry was posted by 정태영 on Monday, June 1st, 2009 at 8:33 PM and is taged under checkbox, css, html, input, javascript.