Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

datalist: display matched choice from query in input text box

I have a form for editing existing data. The user chooses a record and then the form is pre-populated by a database query. Some of the form fields are presented as datalists (allowing pre-populated choices, but users can enter their own).

What I would like to do is to have these datalist elements appear with the current value for that key (from the db) showing in the text box atop the datalist - i.e., in the same manner that an <option> value can be matched to options in a <select> input and show that option in the <select> box when it is rendered.

I've added selected to the options list like this:

<input type="search"
    name="Status"
    placeholder = "~ Status ~"
    id="Status" 
    list="statuslist">

<datalist id="statuslist">
    <select>
      <option value="launched">launched</option>
      <option value="pre-launch" selected>pre-launch</option>
      <option value="no company">no company</option>
    </select>
</datalist>

...but that doesn't seem to do the trick. The datalist input box always displays ~ Status ~ (the placeholder). If I remove the placeholder, it's just blank.

Does datalist support this kind of functionality? How do I make this happen?

like image 299
globalSchmidt Avatar asked Nov 19 '25 09:11

globalSchmidt


1 Answers

datalist.js doesnt update with the selected value, you have to add this after the datalist initialization

//traverse each list
$('input[list]').each(function(){
    // variable for the jquery object of the selected option
    var datalist = $('#' + $(this).attr('list') + ' option:selected');
    // check if value, but also check if option has the attribute "selected"
    if(datalist.val() != 'undefined' && datalist.attr('selected')){
        // update selected to the pre-selected
        $(this).attr('value',datalist.text());
    }
});

updated jsfiddle

Edit: And added support for multiple lists as requested, and fixed error with the datalist.js fallback solution to avoid overwriting the placeholder if nothing selected.

like image 137
turbopipp Avatar answered Nov 21 '25 23:11

turbopipp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!