본문 바로가기
Spring/JavaScript+Jsp(HTMl)

[js] select박스 selected 하는 방법(prop, removeAttribute, setAttribute등 활용)

by snow_hong 2022. 12. 20.

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

댓글