HTML/JS实现工作经历提交填充textarea并支持多次添加预览
实现方案
功能说明
- 该需求可通过原生JS实现,完全符合「添加按钮不触发表单总提交、实时预览已提交工作经历、最终总提交可上传所有数据」的要求
- 核心逻辑:点击添加按钮后读取三个输入框的内容,渲染到下方预览区域,同时把内容存到隐藏的表单数组字段里,总提交的时候会把所有工作经历和表单其他内容一起传到后端
完整可运行代码
HTML部分(在原有基础上新增了预览区和隐藏字段容器)
<form id="resumeForm" action="你的后端提交地址" method="post"> <div> <fieldset> <legend>Work Experience</legend> <p> <label for="occupation">Job Title</label><br> <input type="text" id="occupation" name="occupation"><br> <label for="company">Company Name:</label><br> <input type="text" id="company" name="company"><br> <label for="duties">Duties and Skills Attained:</label><br> <input type="text" id="duties" name="duties"><br> <button type="button" id="generate">Add Work Experience</button> </p> </fieldset> </div> <!-- 已添加工作经历预览区域 --> <div> <h4>已提交的工作经历</h4> <div id="experiencePreview" style="border:1px solid #ccc; padding:10px; min-height:80px; margin:10px 0;"></div> </div> <!-- 隐藏字段容器,用于存储所有工作经历数据,总提交时会同步上传 --> <div id="hiddenExperienceContainer" style="display:none;"></div> <!-- 表单总提交按钮 --> <button type="submit" id="submitAll">提交全部简历内容</button> </form>
JS部分(直接插入到页面<script>标签内即可)
// 记录工作经历的序号 let expIndex = 0; const addBtn = document.getElementById('generate'); const previewBox = document.getElementById('experiencePreview'); const hiddenContainer = document.getElementById('hiddenExperienceContainer'); addBtn.addEventListener('click', function() { // 读取输入内容 const occupation = document.getElementById('occupation').value.trim(); const company = document.getElementById('company').value.trim(); const duties = document.getElementById('duties').value.trim(); // 简单判空,避免提交空内容 if (!occupation || !company || !duties) { alert('请补全所有工作经历信息后再添加'); return; } // 渲染到预览区 const expItem = document.createElement('div'); expItem.style.marginBottom = '10px'; expItem.style.paddingBottom = '10px'; expItem.style.borderBottom = '1px dashed #eee'; expItem.innerHTML = ` <p><strong>岗位:</strong>${occupation}</p> <p><strong>公司:</strong>${company}</p> <p><strong>职责:</strong>${duties}</p> `; previewBox.appendChild(expItem); // 存入隐藏字段,总提交时传给后端 hiddenContainer.innerHTML += ` <input type="hidden" name="experience[${expIndex}][occupation]" value="${occupation.replace(/"/g, '"')}"> <input type="hidden" name="experience[${expIndex}][company]" value="${company.replace(/"/g, '"')}"> <input type="hidden" name="experience[${expIndex}][duties]" value="${duties.replace(/"/g, '"')}"> `; expIndex++; // 清空输入框,方便输入下一份经历 document.getElementById('occupation').value = ''; document.getElementById('company').value = ''; document.getElementById('duties').value = ''; });
补充说明
如果需要支持删除已添加的工作经历,只需要给每个预览项新增删除按钮,点击时同步删除预览节点和对应的隐藏字段即可。
内容的提问来源于stack exchange,提问作者shawn0387
相关产品推荐
相关产品推荐

