如何在JavaScript中实现动态表单提交并统一处理多个表单项?

前端问题涉及表单项的克隆

<form id="questionForm">

        <label for="question">Question:</label>


        <input type="text" id="question" name="question">


        <button type="button" onclick="addQuestion()">Add More</button>

        
    </form>
    <script>
        function addQuestion() {

            let originalForm = document.querySelector("#questionForm");


            let clonedForm = originalForm.cloneNode(true);


            // 重置克隆表单中的输入值


            clonedForm.querySelector("input").value = "";


            document.body.appendChild(clonedForm);


        }
    </script>

修改并且完善代码 要求做到所有克隆的表单项和原来的表单项能在同一个表单内部统一提交

提交按钮只能提交一个表单内容

阅读 2.9k
2 个回答
✓ 已被采纳

1736220771418.png

<!DOCTYPE html>
<html>
<head>
    <style>
        .question-group {
            margin: 10px 0;
        }
        .delete-btn {
            margin-left: 10px;
            color: red;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <form id="questionForm">
        <div id="questionsContainer">
            <div class="question-group">
                <label for="question1">Question:</label>
                <input type="text" name="questions[]" id="question1">
                <span class="delete-btn" onclick="deleteQuestion(this)">×</span>
            </div>
        </div>
        
        <button type="button" onclick="addQuestion()">Add More</button>
        <button type="submit">Submit</button>
    </form>

    <script>
        let questionCount = 1;

        function addQuestion() {
            questionCount++;
            
            const container = document.getElementById('questionsContainer');
            const newQuestionGroup = document.createElement('div');
            newQuestionGroup.className = 'question-group';
            
            newQuestionGroup.innerHTML = `
                <label for="question${questionCount}">Question:</label>
                <input type="text" name="questions[]" id="question${questionCount}">
                <span class="delete-btn" onclick="deleteQuestion(this)">×</span>
            `;
            
            container.appendChild(newQuestionGroup);
        }

        function deleteQuestion(element) {
            const questionGroup = element.parentElement;
            if (document.getElementsByClassName('question-group').length > 1) {
                questionGroup.remove();
            }
        }

        document.getElementById('questionForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const questions = formData.getAll('questions[]');
            
            // 过滤空值
            const validQuestions = questions.filter(q => q.trim() !== '');
            
            console.log('提交的问题:', validQuestions);
            
            // 这里可以加AJAX请求发送数据到服务器
            // fetch('/api/questions', {
            //     method: 'POST',
            //     body: JSON.stringify({ questions: validQuestions }),
            //     headers: {
            //         'Content-Type': 'application/json'
            //     }
            // });
        });
    </script>
</body>
</html>
<!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>
<body>
    <form class="one" method="get">
        <div>愿望:<input type="text" name="dream"></div>
        <button type="button" onclick="addMore()">添加更多</button>
        <button type="submit">提交表单</button>
    </form>
    <script>
        function addMore(){
            console.log(11)            
            const one = document.querySelector('.one')
            const new1 = one.children[0].cloneNode(true)
            one.insertBefore(new1,one.children[1])

        }
    </script>
</body>
</html>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题