1

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 Answers 2

0

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.