select 박스에 selected를 하여 선택하고 싶을 때가 있다.
selectBox가 알아서 selected를 해주지만 안되는 경우가 있다.
그럴경우 prop을 사용하면된다.
- prop()
$('#select1').prop('selected', true); //체크
$('#select1').prop('selected', false); //체크 해제
대부분 이런식으로 하면 된다.
하지만 나는 동적으로 html으로 만들어서 그런지 변경은 되는데 html이 변경이 되지않아서 인식이 잘안된다...ㅠ
그래서 그냥 selected를 다 삭제하고 선택하는 방법을 선택하였다. (정말 하고싶지 않았던 방식ㅜㅜ)
아래 코드와 같이 만들었다.
//class = 'select1' 를 가지고 있는 selectbox가 많음
$(document).on('change','.select1',function(){
var id = $(this).attr('id'); //선택한 selectbox의 id를 가져온다.
var num = $(this).val(); //선택한 slectbox의 값을 가져온다.
//동적으로 하려고 했으나 정적으로...
//만약 option에 selected가 되어잇는 index를 찾을 수 있다면 for문 안해도 됨
// $('#'+id).find("option")[$('#'+id+' option[selected]').index()].removeAttribute('selected');
//으로 해보았지만 생각대로 안되어서 포기
//option에 selected 제거 for문
for(var i=0; i<6; i++ ){
$('#'+id).find("option")[i].removeAttribute('selected');
//$('.select1').eq('1').find("option")[0].removeAttribute('selected'); => 이런식도 가능
//$('#'+id+' option[selected]').index() ==> index를 구해줌(참고)
//$('#'+id+' option[selected]').removeAttribute('selected'); ==> 얜 remove 안됨
}
//selected를 추가
if(num != ''){
$('#'+id).find("option")[$('#'+id+' option[value='+$(this).val()+']').index()].setAttribute('selected','selected');
}else{
$('#'+id).find("option")[0].setAttribute('selected','selected');
}
});
728x90
'Spring > JavaScript+Jsp(HTMl)' 카테고리의 다른 글
[jQuery] 객체 이동함수 focus() - div focus()안되는 현상 해결방법 (0) | 2023.01.19 |
---|---|
[js] table 셀 병합(cell merge) rowspan - 1개 결합 & 2개이상 결합 (0) | 2022.12.28 |
[JS] 동적 html을 만들고 이벤트가 안 될 경우 대처법 (click, change 등) (0) | 2022.12.20 |
[JavaScript] textarea 글자수 제한 / byte 제한 (0) | 2022.10.27 |
[jQuery] 체크박스 선택 및 해제하기 (attr, prop 차이 / 부모의 자식요소들 찾아서 전체 해제하는 법) (0) | 2022.10.07 |
댓글