如何实现input按钮显示文本与实际value属性值不一致
实现方案
完全可以实现,下面是几种常用的落地方案:
- 方案1:替换为
<button>元素(最推荐)<button>元素天生支持显示文本与提交值分离,value属性存套餐ID,标签内部写显示的套餐名即可,示例代码如下:
<form> <button type="button" value="1">basic</button> <button type="button" value="2">advanced</button> <button type="button" value="3">pro</button> <button type="button" value="4">pro+</button> <button type="submit">Create account</button> </form>
后续JS获取选中按钮的value属性值就能拿到套餐ID,展示给用户的是套餐名,不需要额外做映射处理。
- 方案2:保留
<input type="button">,用自定义属性存ID
如果业务要求必须用input标签,可以把套餐ID存在data-*自定义属性中,value属性直接写要显示的套餐名:
<form> <input type="button" value="basic" data-plan-id="1"> <input type="button" value="advanced" data-plan-id="2"> <input type="button" value="pro" data-plan-id="3"> <input type="button" value="pro+" data-plan-id="4"> <button>Create account</button> </form>
提交时读取选中按钮的dataset.planId属性即可拿到对应的套餐ID。
- 方案3:搭配隐藏域实现表单默认提交
如果希望选中的值可以随表单默认提交,不需要额外编写JS读取逻辑,可以新增一个隐藏的input存储选中的套餐ID,点击按钮时自动给隐藏域赋值:
<form> <!-- 隐藏域用来存最终提交的套餐ID --> <input type="hidden" name="plan_id" id="plan_id"> <input type="button" value="basic" onclick="document.getElementById('plan_id').value='1'"> <input type="button" value="advanced" onclick="document.getElementById('plan_id').value='2'"> <input type="button" value="pro" onclick="document.getElementById('plan_id').value='3'"> <input type="button" value="pro+" onclick="document.getElementById('plan_id').value='4'"> <button type="submit">Create account</button> </form>
表单提交时会直接把plan_id的值传给后端,不需要额外处理选中状态的读取逻辑。
小提示:
<input type="button">本身默认不会随表单提交,所以不管用哪种方案,都需要通过JS记录选中值或者通过隐藏域的方式传递实际的套餐ID。
内容的提问来源于stack exchange,提问作者Sofía González
相关产品推荐
相关产品推荐

