본문 바로가기
수업 문제(국비 지원)/JS

[JS] 2022.09.21 (1 부터 100까지의 합,짝수합, 홀수합을 계산, num1의 값을 num2 태그에 복사하기, 바구니 수 구하기)

by byeolsub 2023. 4. 29.

 ❓ 1 부터 100까지의 합,짝수합, 홀수합을 계산하여 result1,result2, result3 에 출력하기

<!DOCTYPE html>
<!--  1 부터 100까지의 합,짝수합, 홀수합을 계산하여  
    result1,result2, result3 에 출력하기-->
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
100까지의 합 : <input type="text" id="result1" ><br>
100까지의 짝수합 : <input type="text" id="result2" ><br>
100까지의 홀수합 : <input type="text" id="result3" ><br>
<script type="text/javascript">
let tot1 = 0;  //변수 선언
let tot2 = 0;
let tot3 = 0;
for(i=1;i<=100;i++) {
	   tot += i
	   if(i%2==0) tot2 += i
	   else tot3 += i
}

result1.value = tot
result2.value = tot
result3.value = tot
</script>
</body>
</html>

❓ num1의 값을 num2 태그에 복사하기

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
   function copyvalue() {
	   num2.value = num1.value;
    }
</script>
</head>
<body>
<h2>num1의 값을 num2 태그에 복사하기</h2>
<input type="text" id="num1">
<input type="text" id="num2">
<input type="button" value="복사하기" onclick="copyvalue()">

</body>
</html>

 ❓ 바구니수 구하기

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>바구니수 구하기</title>
<style type="text/css">
   input {text-align: right;}
   table {	width : 100%; 	border-collapse: collapse;  }
   th,td {
	 border : 3px solid #bcbcbc;
	 text-align: center;
	 padding: 8px;
    }
   th { background-color: #B7F0B1;     color : #353535;     }
   td { background-color: #F2F2F2;}
   caption {	color : #111111;  font-size: 20px;
	       background-color: #FFFFFF;  }
   input[type=text],input[type=password],textarea {
	   width:100%;
   }   
</style>
<script type="text/javascript">
function calc(){
	apple = document.querySelector("#apple").value; //입력한 사과의 갯수. 
	cnt = document.querySelector("#cnt").value;     //선택한 바구니 종류
	let basketcnt = Math.floor(apple/cnt); //소숫점 이하 제거
	if(apple % cnt != 0) basketcnt++;      //나머지가 있는 경우 바구니 한개 더 추가
	document.querySelector("#basketcnt").value=basketcnt
}
</script>
</head>
<body>
<table><caption>바구니수 계산하기</caption>
  <tr><th>바구니당 사과 갯수</th>
      <td><select id="cnt">
        <option value="5">5개</option><option value="10">10개</option>
        <option value="15">15개</option><option value="20">20개</option>
      </select></td></tr>
<tr><th>사과의 총갯수</th>
<td><input type="text" id="apple"></td></tr>      
<tr><td colspan="2" align="right">
  <input type="button" value="바구니수 계산하기"
     onclick="calc()" style="width:100%; text-align:center;">
</td></tr>
<tr><th>필요한 바구니수</th><td>
<input type="text" id="basketcnt">
</td></tr></table></body></html>