带有普通HTML的表单中单选输入中的多个值

我的目标是为我网站上的一个小组件创建一个表单来处理禁用的 JavaScript 体验。目前我有以下表格:

<form method="GET" action="https://mywebsite.com/somedirectory/">

    <input type="radio" name="someParam" value="fruity" />
    <label for="uid1">Fruit</label>

    <input type="radio" name="someParam" value="veggie" />
    <label for="uid2">Vegetable</label>

    ...other radio options

    <input type="submit" value="Submit" />
</form>

单击任一单选选项,然后单击提交按钮将导致:

option 1: https://mywebsite.com/somedirectory/?someParam=fruity
option 2: https://mywebsite.com/somedirectory/?someParam=veggie

如何为每个无线电选项添加另一个值?假设我想传递someOtherParam每个选项唯一的参数,我想将其作为选项的输出:

option 1: https://mywebsite.com/somedirectory/?someParam=fruity&someOtherParam=apple
option 2: https://mywebsite.com/somedirectory/?someParam=veggie&someOtherParam=pepper

我尝试过的是:

<input type="radio" name="someParam" value="fruity&someOtherParam=apple" />
<input type="radio" name="someParam" value="veggie&someOtherParam=pepper" />

但是,&符号被转换为%26链接内部,感觉太hacky了。有没有更好的方法来实现这一目标?另外,有没有办法确保仅在选择单选选项后才启用提交按钮?

PS 我的目标是纯 HTML 体验,不涉及 Javascript。那可能吗?

回答

我很确定这在不使用 JS 的现代浏览器中是不可能的。也许在旧浏览器上你可以用 CSS 做一些技巧,display:none因为它过去不发送带有 的字段display:none,但现在这不是一个选项。

如果您可以允许 Javascript,您可以为每个单选选项添加一个数据属性,并使用它在更改时填充额外的隐藏输入。

document.querySelectorAll('input[type=radio][name="someParam"]')
  .forEach(radio => radio.addEventListener('change', (event) =>
    document.getElementById('someOtherParam').value = event.target.dataset.extraValue
  ));
<form method="GET" action="https://mywebsite.com/somedirectory/">
  <input type="radio" name="someParam" value="fruity" />
  <label for="uid1">Fruit</label>

  <input type="radio" name="someParam" value="veggie" />
  <label for="uid2">Vegetable</label>

  <input type="hidden" name="someOtherParam">

  <input type="submit" value="Submit" />
</form>


以上是带有普通HTML的表单中单选输入中的多个值的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>