HTML datalist with fallback causes duplicate query string parameters

ε祈祈猫儿з 提交于 2019-12-13 02:27:08

问题


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>

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.

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=.

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?


回答1:


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.

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.




回答2:


I don't know if you're still looking for a solution or if my answer even supports older browser, but it was exactly what I was looking for. I used selectize.

$('#sex').selectize({create: true});
<select id="sex">
  <option value="" />
  <option>Female</option>
  <option>Male</option>
</select>


来源:https://stackoverflow.com/questions/29756791/html-datalist-with-fallback-causes-duplicate-query-string-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!