Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can HTML5 datalist differentiate value and option text?

The list attribute / datalist element of HTML5 forms shows a dropdown menu of choices one can pick from, edit, and even type in some text. All this can be achieved at once with a clean and powerful code:

<input list="states">
<datalist id="states">
    <option value="One">
    <option value="Two">
</datalist>

However, how to make such a form send a value which is different from the option text, as in the usual select / option (below)?

<select>
    <option value="1">One</option>
    <option value="2">Two</option>
</select>
like image 397
Alex Avatar asked Aug 27 '13 11:08

Alex


People also ask

What can you achieve with HTML Datalist tag?

The <datalist> tag is used to provide an "autocomplete" feature for <input> elements. Users will see a drop-down list of pre-defined options as they input data.

What is the difference between Datalist and dropdown?

Generally, both the tags are used for choosing an option from the given list. But the main difference between both is that in the <datalist> tag the user can enter its own input and add that as an option with the help of the <input> element whereas the <select> tag doesn't provide this feature.

What is alternative for Datalist?

Alternatives to <datalist> If you can actually limit the user's input to the predefined options, and you don't need free-entry, you can simply use the standard <select> element. If you need type-entry autocomplete, the most widely supported solution is Javascript.


2 Answers

Seems you can't with pure HTML without using some JS+CSS help.

try this i hope its help you.

html

<input id="datalisttestinput" list="stuff" ></input>
        <datalist id="stuff">
            <option id="3" value="Collin" >
            <option id="5" value="Carl">
            <option id="1" value="Amy" >
            <option id="2" value="Kristal">
        </datalist>

script

function GetValue() {
            var x = $('#datalisttestinput').val();
            var z = $('#stuff');
            var val = $(z).find('option[value="' + x + '"]');
            var endval = val.attr('id');
            alert(endval);
        }

Best Wishes Kumar

like image 148
Kumar Shanmugam Avatar answered Oct 04 '22 19:10

Kumar Shanmugam


Below is Kumah's modified answer that uses a hidden field to contain the value which ultimately gets sent to the server.

$('#inputStates').change(function(){
    var c =  $('#inputStates').val();
    $('#inputStates').val(getTextValue());
    $('#statesHidden').val(c);
});

function getTextValue(){
  var val =  $('#inputStates').val();
  var states = $('#states');
  var endVal = $(states).find('option[value="' + val + '"]');
  //depending on your logic, if endVal is empty it means the value wasn't found in the datalist, you can take some action here
  return endVal.text();
}
like image 27
user1587439 Avatar answered Oct 04 '22 17:10

user1587439