본문 바로가기
개발/Javascript

input component development

by Neya31 2024. 11. 30.
728x90
반응형
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dynamic Input Components with Select</title>
</head>
<body>

<!-- 여러 개의 영역을 미리 준비 -->
<div id="section1"></div>
<div id="section2"></div>
<div id="section3"></div>

<!-- 제출 버튼 -->
<button onclick="submitForm()">Submit</button>

<script>
    const inputComponents = [
        { id: 1, type: 'text', placeholder: 'Enter your name', container: 'section1', name: 'name' },
        { id: 2, type: 'number', placeholder: 'Enter your age', container: 'section2', name: 'age' },
        { id: 3, type: 'email', placeholder: 'Enter your email', container: 'section1', name: 'email' },
        { id: 4, type: 'password', placeholder: 'Enter your password', container: 'section3', name: 'password' },
        { id: 5, type: 'tel', placeholder: 'Enter your phone number', container: 'section2', name: 'phone' },
        { id: 6, type: 'date', placeholder: 'Select a date', container: 'section1', name: 'date' },
        { id: 7, type: 'datetime-local', placeholder: 'Select date and time', container: 'section3', name: 'datetime' },
        { id: 8, type: 'checkbox', label: 'Agree to terms', container: 'section2', name: 'terms' },
        { id: 9, type: 'radio', name: 'gender', values: ['male', 'female', 'other'], label: 'Gender', container: 'section1' },
        { id: 10, type: 'file', placeholder: 'Upload a file', container: 'section3', name: 'file' },
        { id: 11, type: 'select', name: 'country', label: 'Country', container: 'section1', apiUrl: 'https://your-server-url.com/api/countries' },
    ];

    inputComponents.forEach(component => {
        const container = document.getElementById(component.container);
        let element;

        if (component.type === 'checkbox' || component.type === 'radio') {
            element = document.createElement('fieldset');
            const legend = document.createElement('legend');
            legend.textContent = component.label;
            element.appendChild(legend);

            component.values.forEach((value, index) => {
                const input = document.createElement('input');
                input.type = component.type;
                input.id = `input-${component.id}-${index}`;
                input.name = component.name;
                input.value = value;
                
                const label = document.createElement('label');
                label.setAttribute('for', input.id);
                label.textContent = value;
                
                element.appendChild(input);
                element.appendChild(label);
                element.appendChild(document.createElement('br'));
            });

        } else if (component.type === 'select') {
            element = document.createElement('select');
            element.id = `input-${component.id}`;
            element.name = component.name;

            // API에서 데이터 가져오기
            fetchOptions(component.apiUrl, element);
            
        } else {
            element = document.createElement('input');
            element.type = component.type;
            element.id = `input-${component.id}`;
            element.placeholder = component.placeholder || '';
            element.name = component.name;
        }

        container.appendChild(element);
        container.appendChild(document.createElement('br'));
    });

    // 서버에서 데이터를 가져와 select에 옵션을 추가하는 함수
    async function fetchOptions(url, selectElement) {
        try {
            const response = await fetch(url);
            const data = await response.json();  // JSON 형식으로 응답받기
            
            // 기존 옵션을 초기화
            selectElement.innerHTML = '';

            // 옵션 추가 (예시: 데이터가 { id: 1, name: 'Country 1' } 형식일 때)
            data.forEach(item => {
                const option = document.createElement('option');
                option.value = item.id;  // id 값을 value로 사용
                option.textContent = item.name;  // name 값을 텍스트로 사용
                selectElement.appendChild(option);
            });
        } catch (error) {
            console.error('Error fetching options:', error);
        }
    }

    // 폼 데이터를 수집하고 서버로 전송하는 함수
    function submitForm() {
        const formData = {};

        inputComponents.forEach(component => {
            const element = document.getElementById(`input-${component.id}`);

            if (component.type === 'checkbox') {
                formData[component.name] = element.checked;
            } else if (component.type === 'radio') {
                const selectedRadio = document.querySelector(`input[name="${component.name}"]:checked`);
                if (selectedRadio) {
                    formData[component.name] = selectedRadio.value;
                }
            } else if (component.type === 'file') {
                const fileInput = document.getElementById(`input-${component.id}`);
                formData[component.name] = fileInput.files[0];
            } else {
                formData[component.name] = element.value;
            }
        });

        console.log(formData);

        // 서버로 데이터 전송 (예시: fetch 사용)
        fetch('https://your-server-url.com/submit', {
            method: 'POST',
            body: JSON.stringify(formData),
            headers: {
                'Content-Type': 'application/json',
            },
        })
        .then(response => response.json())
        .then(data => {
            console.log('Success:', data);
        })
        .catch(error => {
            console.error('Error:', error);
        });
    }
</script>

</body>
</html>
반응형

'개발 > Javascript' 카테고리의 다른 글

import 자동생성  (0) 2024.12.01
input Components 관리  (0) 2024.11.30
input과 form 연결  (0) 2024.11.30
Form Data.  (0) 2024.11.30
[javascript] ajax 폼 전송  (0) 2022.11.06