具有回退的HTML数据列表会导致重复的查询字符串参数 [英] HTML datalist with fallback causes duplicate query string parameters
问题描述
我正在尝试为较旧的浏览器实现带有内置后备功能的datalist
元素,如w3
I'm trying to implement a datalist
element with a built-in fallback for older browsers, as demonstrated on the w3 datalist element spec:
<form action="http://example.com/" method="GET">
<label>
Sex:
<input name="sex" list="sexes" />
</label>
<datalist id="sexes">
<label>
or select from the list:
<select name="sex">
<option value="" />
<option>Female</option>
<option>Male</option>
</select>
</label>
</datalist>
<input type="submit" />
</form>
但是,<input type="text">
和datalist
两者都具有相同名称(后备要求)的组合会导致"sex"参数在查询字符串中出现两次.
However, the combination of an <input type="text">
and the datalist
both with the same name (required for the fallback) cause the "sex" parameter to appear twice in the query string.
表单提交不适用于SO代码段,因此请参阅此小提琴.提交男性"时,网络标签会显示一个关于提交的请求,内容为http://www.example.com/?sex=male&sex=
.
Form submit didn't work in SO code snippet, so see this fiddle instead. When submitting "Male" the network tabs shows a request on submit that says http://www.example.com/?sex=male&sex=
.
这会在后端代码中引起一些奇怪的行为(不幸的是,我现在无法修改).如何在保持后备状态的同时防止double参数?
This causes some wonky behavior in the backend code (that I can't modify right now unfortunately). How can I prevent the double parameter while keeping a fallback?
推荐答案
我最终通过使用"sex"值设置单个<input type="hidden">
而不是使用select
和input type="text"
作为源来解决了该问题.价值.更改后一个值时,我会将值复制到隐藏的输入中.
I ended up solving it by setting a single <input type="hidden">
with the "sex" value instead of using the select
and input type="text"
as a source for the value. On change of either of the latter, I copy the value to the hidden input.
我碰巧已经包含了jQuery,所以这是我使用的解决方案:
I happened to have jQuery already included so here's the solution I used:
$('#myForm input, #myForm select').change(function() {
$('#sex').val(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="http://www.example.com/" method="GET" id="myForm">
<label>
Sex:
<input list="sexes" />
</label>
<datalist id="sexes">
<label>
or select from the list:
<select>
<option value="" />
<option>Female</option>
<option>Male</option>
</select>
</label>
</datalist>
<input type="hidden" name="sex" id="sex" />
<input type="submit" />
</form>
我仍然愿意寻求更好的解决方案.
I'm still open to better solutions.
这篇关于具有回退的HTML数据列表会导致重复的查询字符串参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!