Forum Moderators: open

Message Too Old, No Replies

Datalists

         

csdude55

4:26 am on Feb 22, 2020 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



This was a neat little discovery:

<input type="text" name="foo" list="bar" placeholder="Select One or Create a New One">
<datalist id="bar">
<option value="First">First</option>
<option value="second">Second</option>
</datalist>


In action:

[jsfiddle.net...]

It's not compatible with <= IE9 so I can't rely on it TOO heavily, but it's cool when it's not really critical for the user to have a select menu.

But here's the question. If the "value" attribute and the value given are the same then the list shows the one label (eg, "First"), but if they don't match then it shows both (eg, "second Second"). In practice, I have a section where the value attribute looks more like "title|:|link|:|something else|:|this is a comment", and I use onChange to split that value up and populate other fields.

Obviously, though, I don't want the user to see that; I just want them to see the value I've given between <option ...>Value Given</option>.

Any idea how I might control what is actually shown?

lammert

10:31 am on Feb 23, 2020 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



The datalist tag is introduced to implement auto-complete functionality. Therefore the list will only contain items where the string entered in the edit box matches part or whole of the item strings. So this is probably not the right tag for your intended purpose.

csdude55

8:01 pm on Feb 23, 2020 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I was able to work around it by building the content as an object in Javascript... a little tough to read, I think, so I might regret this in a year or two! But it works and has the look I liked:

<input type="text" name="foo" list="bar" placeholder="Select One or Create a New One"
onChange="changeMsg(this.value)">
<datalist id="bar"></datalist>

<script>
var obj {
"First" :
"title|:|link|:|something else|:|this is a comment",
"Second" :
"Next title|:|link|:|something else|:|this is another comment"
}

for (const item of Object.keys(obj)) {
var option = document.createElement('option');
option.value = item;

document.getElementById('bar').appendChild(option);
}

function changeMsg(str) {
document.formName.textareaName.value = obj[str];
}

</script>

I actually store the data for obj{} in MySQL and build it in PHP, then use json_encode to create a PHP string that I can just plug in. So the code is really pretty slim on my end.

There are a lot of nifty options for INPUT that I would love to use, but they don't work with IE :'-( I just discovered this one a few days ago, but there's also:

<input type="color">
<input type="date">
<input type="range">

[jsfiddle.net...]

Cool stuff if IE would work with it... maybe in about 10 years when IE11 is negligible >:-(