Setting Hidden Datalist Option Values

A few datalist labels with hide value

To accomplish the goal you need to assign the event handler to ALL suitable input elements that you wish to include this functionality. Use querySelectorAll to obtain such a nodelist and iterate through to assign your input event handler.

I simplified the IDs/data-ids for brevity and convenience. Dataset attributes can be repeated so it is acceptable to use data-id=x on multiple elements where it would not be legitimate to use id=x on more than one. This helps later with selecting the hidden element and means simpler HTML code.

The comments throughout the inputhandler function should help illuminate what is happening at each point.

document.addEventListener('DOMContentLoaded',(e)=>{

const inputhandler=function(e){
// Find the appropriate datalist associated with current text input element.
let list=document.querySelector( 'datalist#' + this.getAttribute('list') );
// Find all the options within this datalist.
let options=list.querySelectorAll('option');
// Find the appropriate hidden input field based upon list attribute from current text input element.
let input=document.querySelector('input[type="hidden"][ data-list="'+this.getAttribute('list')+'" ]');

// Set the value of the hidden input to that of text element.
input.value=this.value;

// Iterate through `some` of the options - stop when a condition is met.
Array.from( options ).some( opt=>{
if( opt.textContent.trim()===this.value.trim() ){
// condition has been satisfied - set hidden input element value
input.value=opt.dataset.value;

// display formatted message in the console
console.log(
'The hidden field "%s" has been assigned "%s" as it\'s new value',
input.name,
input.value
);

// stop iteration of nodelist - job done.
return true;
}
})
};

document.querySelectorAll( 'input[list]' ).forEach( input=>input.addEventListener('input',inputhandler));
})
<form method='post' action="<?php echo $adresstrust; ?>">
<input type='text' list='list1' />
<datalist id='list1'>
<option data-value='42'>The answer
<option data-value='43'>The answer3
<option data-value='44'>The answer4
</datalist>

<input type='text' list='list2' />
<datalist id='list2'>
<option data-value='42'>The answer
<option data-value='43'>The answer3
<option data-value='44'>The answer4
</datalist>

<input type='hidden' name='answer' data-list='list1' />
<input type='hidden' name='answer2' data-list='list2' />

<input type='hidden' name='ala' value='tutaj' />
<input type='submit' value='Start' />
</form>

HTML datalist hide option from list

<option>s can be omitted from the list using the disabled attribute.

document.getElementById('toggle').addEventListener('change', (e) => {
let opt = document.querySelector('option[value=Chrome]')
opt.toggleAttribute('disabled', e.target.checked)
})
<input list="test" />
<datalist id="test">
<option value="Internet Explorer">
<option value="Firefox">
<option value="Chrome" disabled>
<option value="Opera">
<option value="Safari">
</datalist>

<label>
<input checked type="checkbox" id="toggle" />
disable Chrome
<labe>

Show datalist labels but submit the actual value

Note that datalist is not the same as a select. It allows users to enter a custom value that is not in the list, and it would be impossible to fetch an alternate value for such input without defining it first.

Possible ways to handle user input are to submit the entered value as is, submit a blank value, or prevent submitting. This answer handles only the first two options.

If you want to disallow user input entirely, maybe select would be a better choice.


To show only the text value of the option in the dropdown, we use the inner text for it and leave out the value attribute. The actual value that we want to send along is stored in a custom data-value attribute:

To submit this data-value we have to use an <input type="hidden">. In this case we leave out the name="answer" on the regular input and move it to the hidden copy.

<input list="suggestionList" id="answerInput">
<datalist id="suggestionList">
<option data-value="42">The answer</option>
</datalist>
<input type="hidden" name="answer" id="answerInput-hidden">

This way, when the text in the original input changes we can use javascript to check if the text also present in the datalist and fetch its data-value. That value is inserted into the hidden input and submitted.

document.querySelector('input[list]').addEventListener('input', function(e) {
var input = e.target,
list = input.getAttribute('list'),
options = document.querySelectorAll('#' + list + ' option'),
hiddenInput = document.getElementById(input.getAttribute('id') + '-hidden'),
inputValue = input.value;

hiddenInput.value = inputValue;

for(var i = 0; i < options.length; i++) {
var option = options[i];

if(option.innerText === inputValue) {
hiddenInput.value = option.getAttribute('data-value');
break;
}
}
});

The id answer and answer-hidden on the regular and hidden input are needed for the script to know which input belongs to which hidden version. This way it's possible to have multiple inputs on the same page with one or more datalists providing suggestions.

Any user input is submitted as is. To submit an empty value when the user input is not present in the datalist, change hiddenInput.value = inputValue to hiddenInput.value = ""


Working jsFiddle examples: plain javascript and jQuery

Hide datalist options when user starts typing

One way you can do this is to chage the datalist id when there is a value in input. If there is no value then change the id back so that they can choose the options in the datalist rather than type a new one.

function hideList(input) { var datalist = document.querySelector("datalist"); if (input.value) {  datalist.id = "";       } else {  datalist.id = "talk-list"; }}
<input id ="userText" name="userText" type="text" list = 'talk-list' oninput="hideList(this)"></input>    <span class = "dropdown" title = "Saved Talk"><datalist id = 'talk-list'><option>Apple</option><option>Ball</option><option>Calculator</option><option>Donkey</option></datalist></span>    <button id="speakText" class="toolbutton" title="Speak">Speak</button>


Related Topics



Leave a reply



Submit