HTML datalist with fallback causes duplicate query

2019-07-30 01:31发布

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?

2条回答
贪生不怕死
2楼-- · 2019-07-30 02:13

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>
查看更多
我想做一个坏孩纸
3楼-- · 2019-07-30 02:32

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.

查看更多
登录 后发表回答