Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

JavaScript에서 배열로 라디오 버튼을 동적으로 생성하는 방법

JavaScript에서 배열에 담긴 데이터를 기반으로 라디오 버튼을 동적으로 생성하려면 createElement()appendChild() 메서드를 활용하면 됩니다. 이 두 메서드를 조합하면 서버 응답이나 사용자 입력에 따라 폼 요소를 유연하게 만들어낼 수 있습니다.

예제

다음은 전체 코드입니다 −

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<link rel="stylesheet"
href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
</body>
<script>
   var gender = ['Male', 'Female'];
   gender.forEach((genederValue, i) => {
      var labelValue = document.createElement('label');
      labelValue.innerHTML = genederValue;
      var inputValue = document.createElement('input');
      inputValue.type = "radio";
      inputValue.name = genederValue;
      inputValue.genederValue = i;
      document.body.appendChild(labelValue);
      document.body.appendChild(inputValue);
   });
</script>
</html>

코드 설명

  • 선택 옵션인 'Male'과 'Female' 값을 gender 배열에 담습니다.
  • forEach() 메서드로 배열의 각 요소를 순회하면서 반복 작업을 수행합니다.
  • createElement()를 사용해 label과 input 요소를 생성하고, input의 type 속성을 "radio"로 지정합니다.
  • appendChild()를 통해 완성된 label과 input 요소를 문서의 body에 차례대로 추가합니다.

위 프로그램을 실행하려면 파일 이름을 anyName.html(index.html)로 저장한 후 해당 파일을 마우스 오른쪽 버튼으로 클릭하세요. 그다음 VS Code 편집기에서 “Open with Live Server” 옵션을 선택하면 브라우저에서 바로 결과를 확인할 수 있습니다.

출력

이 코드를 실행하면 다음과 같은 결과가 출력됩니다 −

JavaScript에서 배열로 라디오 버튼을 동적으로 생성하는 방법