본문 바로가기

개발일지/JavaScript + jquery

[js] slect문에서 다중선택 입력 및 출력하기(multiple)

 

[js] select에서 단일 입력 및 출력(전공선택)

전공 체크 전공 컴퓨터 정보통신 법학 경영학 영문학 var idx = ff.ss.options[ff.ss.selectedIndex].value; ff.ss.셀렉트 되어 있는 것을 찾는다. value 그걸 갖고와라 ff 폼 이름이 s..

practice365.xyz

select 단일선택에 이어서 다중선택이라면 어떻게 출력을 해야할까요? 전에 사용했던 예시를 이용해서 만들어봤습니다.

 

 

<select 단일의 경우>

<script>
	function Check(ff){
		var idx = ff.ss.options[ff.ss.selectedIndex].value;
		document.write(idx);
	}
</script>

비교적 짧고 쉬웠던 코드

 

 

<select 중복 선택의 경우>

<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script>
	function check(ss){ //똑같은 변수로 바꿔도 상관 없음
		var result = [];
		var options = ss; //select를 options에 넣었음
		var opt;
		ilen = options.length; //ilen에다가 길이를 넣음
		for(i=0; i<ilen; i++){
			opt = options[i]; //따로 떨어뜨리기 위해서 opt에 집어넣는다.
			if(opt.selected){ result.push(opt.value); } //result에다가 value값을 밀어넣어줘(push)..
			//push로 저장 받은 값은 stack에 들어간다.
			}
			document.write(result);
		}
  </script>
 </head>
 <body>
  <form>
  	<fieldset>
	<legend></legend>
	<select id="ss" multiple="multiple">
		<option value="컴퓨터">컴퓨터</option>
		<option value="경영학">경영학</option>
		<option value="법학">법학</option>
		<option value="영문학">영문학</option>
		<option value="정보통신">정보통신</option>
	</fieldset>
		<input type="button" value="전공" onclick="check(ss);">
  </form>
 </body>
</html>

 

1. 초기화 및 불러오기

읽는 과정에서 1차원 배열을 쓸 거라서 

result = [];으로 초기화를 시켜준다.


options = ss;
불러와서 읽으려고 옵션에 ss를 넣어준다.  

opt 초기화는 출력시 서로 떨어뜨리고 쉼표(,)를 찍기 위해서다

 

ilen 길이 값을 넣을 변수로 

options.length; 길이를 잴 때 쓴다.

옵션 값이 추가되어도 이 부분은 바뀌지 않는다. 

 

 

2. 사용자가 선택한 값을 저장한다.

i=0부터 시작되는 이유는 배열이 0부터 시작하기 때문에

opt = options[i]; 각 값들을 출력했을 때 보기 좋게 하기 위해서(띄어쓰기와 쉼표) opt에 집어넣는다.

 

if(opt.selected){ result.push(opt.value); }

opt.selected 체크를 해서 내가 선택한 값

opt.value값을 result에다가 밀어줘(push)

//push로 저장 받은 값은 stack에 들어간다.

selected는 select문에서만 쓰인다.

 

3. 출력
document.write(result);

 

너무 길고 필요 없는 값이 있기에 줄여본다.

 

<코드 줄이기>

  <script>
	function check(ss){ 
		var result = "";
		for(i=0; i<ss.length; i++){
			if(ss[i].selected) { result= result + ss[i].value + "\n";}
			//push를 뺄 수 있다. 대신 컴마가 없어지니까 "\n" 이걸 넣음
			}
			document.write(result);
		}
  </script>


var result = "";

출력할 값이라 있어야 하지만 [] 대신에 ""도 가능하다.

 

for(i=0; i<ss.length; i++){}

ilen을 굳이 넣지 않고 바로 ss.length 길이를 갖고 올 수 있다. 


if(ss[i].selected) 

ss[i].selected 따로 변수를 만들지 않고 바로 불러와서 체크 할 수 있다.

 

{ result = result + ss[i].value + "\n"; }
push를 뺄 수 있다. 바로 value 값을 불러와서 result에 넣는다. 대신 컴마가 없어지니까 "\n" 이걸 넣으면 된다.

 

{ result += ss[i].value + "\n"; }

이것도 한 번 더 줄일 수 있다. 

 

document.write(result);
출력