DropsBrowse Pastes
Login with GitHub

demo for poll-front

February 17th, 2022Views: 16(0 unique)HTML
<!DOCTYPE html>

<html>

<head>
    <meta charset="utf-8">
    <title>poll-front</title>
</head>

<body>
    <button type="button" id="add">Add</button>
    <form id="q-form">
        <button>Submit</button>
    </form>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script>
        const add = document.querySelector('#add')
        const qForm = document.querySelector('#q-form')

        add.addEventListener('click', () => {
            const questionType = document.createElement('select')
            const questionContents = document.createElement('input')

            questionType.innerHTML = '<option value="text">Text</option><option value="checkbox">checkbox</option>'
            questionType.addEventListener('change', () => {
                questionContents.type = questionType.selectedOptions[0].value
                if (questionContents.type === 'checkbox') {
                    const checkboxValue = document.createElement('input')
                    checkboxValue.addEventListener('input', () => {
                        questionContents.value = checkboxValue.value
                    })
                    qForm.appendChild(checkboxValue)
                }
            })
            qForm.appendChild(questionType)
            qForm.appendChild(questionContents)
        })

        qForm.addEventListener('submit', event => {
            event.preventDefault()
            const questionValues = qForm.querySelectorAll('input')
            const questionTypes = qForm.querySelectorAll('select')
            let questions = []
            for (let i = 0; i < questionTypes.length; i++) {
                questions.push({
                    id: i + 1,
                    type: questionTypes[i].selectedOptions[0].value,
                    contents: questionValues[i].value
                })
            }
            console.log(questions)
            axios.post('http://127.0.0.1:8080/questions', questions)
        })
    </script>
</body>

</html>