如何获取3个表单字段输入值存入数组用于API调用
实现思路
- 首先修正现有HTML的语法错误:原提交按钮写法有误,
input为自闭合标签,多余的Search</button>片段会导致DOM结构异常,建议直接改用语义更清晰的button标签做提交按钮 - 给表单绑定
submit事件(比单独监听按钮点击体验更好,支持回车触发提交),触发时先阻止表单默认的页面刷新跳转行为 - 选中所有食材输入框,遍历提取输入值,做去空格、空值过滤处理后存入数组
- 拿到存储输入值的数组后,直接拼接参数发起API请求即可
修正后的完整代码
HTML部分
<h2>ENTER YOUR INGREDIENTS</h2> <div class="left"></div> <div class="right"> <form class="search-form"> <input type="text" class="field" id="form1" placeholder="First Ingredient"> <input type="text" class="field" id="form2" placeholder="Second Ingredient"> <input type="text" class="field" id="form3" placeholder="Third Ingredient"> <button type="submit" id="btn">Submit</button> </form> </div>
JavaScript部分
const searchForm = document.querySelector('.search-form'); // 监听表单提交 searchForm.addEventListener('submit', function(e) { // 阻止默认跳转刷新 e.preventDefault(); // 提取所有输入框的值,处理后存入数组 const ingredients = Array.from(document.querySelectorAll('.field')) .map(input => input.value.trim()) // 去除输入前后空格 .filter(val => val); // 过滤空值,避免空字符串进入参数 // 基础校验:至少输入1种食材 if (ingredients.length === 0) { alert('请至少输入一种食材'); return; } // 后续API调用直接使用ingredients数组即可,示例: console.log('提交的食材数组:', ingredients); // 接口请求示例: // const apiUrl = `/api/recipe/search?items=${encodeURIComponent(ingredients.join(','))}`; // fetch(apiUrl).then(res => res.json()).then(data => { // // 处理接口返回结果 // }) })
关键逻辑说明
- 用
Array.from将选择器返回的NodeList节点集合转为标准数组,才能直接调用map、filter等数组方法 - 增加
trim()处理是为了避免用户误输入的首尾空格污染参数 - 空值过滤逻辑可以自动跳过用户未填写的输入框,不需要强制要求3个字段都填
- 监听
submit事件可以覆盖回车提交的场景,不需要额外给输入框绑定键盘事件
内容的提问来源于stack exchange,提问作者lukesudom
相关产品推荐
相关产品推荐

