如何在用户填写表单时按需展示输入内容?
解决方案
要实现仅展示用户已填写/选择的对应内容,同时保持合并事件处理的代码结构,可以通过条件判断筛选有效内容,只将有值的部分拼接后展示,具体实现如下:
修改后的完整代码
HTML部分
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js" integrity="sha512-STof4xm1wgkfm7heWqFJVn58Hm3EtS31XFaagaa8VMReCXAkQnJZ+jEy8PCC/iT18dFy95WcExNHFTqLyp72eQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <form id="secondform"> <input id="mysecondtext" type="text"> <select id="mysecondselect" name="select[]" class="select"> <!-- 给默认选项设置空value,方便判断是否选择了有效选项 --> <option selected disabled="disabled" value="">select your product</option> <option value="https://google.com/">My product</option> <option value="https://google.fr/">My second product</option> </select> </form> <div id="secondresult"></div>
JavaScript部分
function onChange(){ // 用数组存储需要展示的有效内容片段 var displayParts = []; // 处理文本输入:仅当输入内容非空(去除首尾空格后)时加入片段 var inputText = $('#mysecondtext').val().trim(); if (inputText) { displayParts.push(inputText + '?'); } // 处理下拉选择:仅当选中有效选项(value非空)时加入片段 var selectedValue = $('#mysecondselect').val(); if (selectedValue) { displayParts.push('utm_source=' + selectedValue); } // 将有效片段拼接后展示,无有效内容则清空结果区域 $('#secondresult').html(displayParts.join('')); } // 绑定所有表单元素的事件 $('#secondform select').on('change', onChange); $('#secondform input').on('input', onChange);
核心逻辑说明
- 有效内容判断:
- 文本输入:用
trim()去除首尾空格,避免空输入或纯空格被误判为有效内容,仅当内容非空时生成对应的展示片段。 - 下拉选择:给默认选项设置
value="",通过判断val()是否非空,确定用户是否选择了有效选项,仅选中有效选项时生成对应的utm片段。
- 文本输入:用
- 动态拼接展示:
- 用数组存储所有有效展示片段,最后通过
join('')拼接成完整内容,确保只有用户已填写/选择的部分才会被展示。 - 如果没有任何有效内容,结果区域会自动清空,不会显示多余的符号(比如
?或空的utm参数)。
- 用数组存储所有有效展示片段,最后通过
扩展适配多字段
如果表单有更多字段,只需在onChange函数中重复类似的判断逻辑:
// 示例:新增一个文本字段和下拉字段 var anotherText = $('#anothertext').val().trim(); if (anotherText) { displayParts.push('&another_param=' + anotherText); } var anotherSelect = $('#anotherselect').val(); if (anotherSelect) { displayParts.push('&utm_medium=' + anotherSelect); }
内容的提问来源于stack exchange,提问作者blogob
相关产品推荐
相关产品推荐

