/    Sign up×
Community /Pin to ProfileBookmark

Datalist required=”data-value”

I am trying to use “datalist” in html as a “select”.
The value selected in the datalist should be verified by a “data-value”.
So, there should not be any ad-hoc entering. You must select a existing value.

My current solution allow non existing values.

Something like this:
`<input list=”jobs” placeholder=”Select Job” required=”data-value”>`

Fiddle: https://jsfiddle.net/brsf14yu/

Is this possible?

to post a comment
HTML

11 Comments(s)

Copy linkTweet thisAlerts:
@JMRKERJul 24.2020 — I appears that you have asked the same question on another forum

See: [https://www.sitepoint.com/community/t/validate-data-value-in-a-html-datalist/355469](url)

Was that answer not acceptable? Are you trying to do some sort of coder vs. coder comparisons?

I played around with the code and came up with the following.

The approach is a bit different from your original post but can be modified as needed if you see the purpose of the suggested changes.

> <!DOCTYPE html><html lang="en"><head><title> Test Page </title>

<meta charset="UTF-8">

<meta name="viewport" content="width-device-width,initial-scale=1.0, user-scalable=yes"/>

<!--

From: https://www.sitepoint.com/community/t/validate-data-value-in-a-html-datalist/355469

And: https://jsfiddle.net/brsf14yu/

-->

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300">

<style>

/* datalist { display: block; } /* for testing purposes only -- normally display: none */


  • * {

    font-family: 'Source Sans Pro', sans-serif;

    font-weight: 300;

    font-size: 18px;

    }

    input[type=text],

    input [ list ] {

    color: #f0f0f0;

    font-size: 18px;

    padding: 10px;

    max-height: 56px;

    width: 350px;

    background: #555;

    -webkit-appearance: none;

    appearance: none;

    border: none;

    }

    #submit{

    color: #f0f0f0;

    font-size: 18px;

    padding: 10px;

    max-height: 56px;

    width: 370px;

    background: #555;

    -webkit-appearance: none;

    appearance: none;

    border: none;

    }

    </style>

    </head><body>

    <form action="javascript:alert('Success')" method="post"

    onsubmit="return checkInputs()"> <!-- target="_self" -->


    <input id="job" list="jobs" placeholder="Select Job" required="data-value">

    <datalist id="jobs"></datalist>

    <br>

    <input id="code" list="codes" placeholder="Select Code" required="data-value">

    <datalist id="codes"></datalist>

    <br>

    <input id="note" type="text" placeholder="Note" required>

    <br>

    <input type="submit" value="Submit"> <!-- onsubmit="return checkInputs()" -->

    <br>


  • Remove following after testing<br>

    <!-- for testing purposes -->

    <input id="auto" list="autos" placeholder="Car" required="data-value" />

    <datalist id="autos"></datalist>

    </form>

    <script>

    console.clear();

    function checkInputs() {

    var respJob = document.getElementById('job'),

    respCode = document.getElementById('code'),

    respNote = document.getElementById('note');

    var respCar = document.getElementById('auto'); // for testing purposes only

    const errMsg = 'Please select a valid value';

    var err = 0; // represents no errors

    if (!listJobs.includes(respJob.value)) { err = 1; respJob.setCustomValidity(errMsg); }

    else { respJob.setCustomValidity(''); }

    if (!listCodes.includes(respCode.value)) { err = 2; respCode.setCustomValidity(errMsg); }

    else { respCode.setCustomValidity(''); }

    if (!listCars.includes(respCar.value)) { err = 3; respCar.setCustomValidity(errMsg); }

    else { respCar.setCustomValidity(''); }

    if (err != 0) { // error noted

    alert('Error - invalid entry '+err+' - '+errMsg);

    return false;

    } else { // all OK

    alert(${respJob.value}n${respCode.value}n${respNote.value}n${respCar.value});

    return true;

    }

    // return (err !== 0);

    }

    function createOptions(listIDS,Ary) {

    const list = document.getElementById(listIDS);

    Ary.forEach(item => {

    let option = document.createElement('option');

    // [n,v] = item.split(':'); option.value = item.replace(':',' '); option.textContent = v;

    option.value = item; option.textContent = item;

    list.appendChild(option);

    });

    }

    const listJobs = ['42 Web','43 Print'];

    const listCodes = ['Project Management','COPY'];

    const listCars = ['1:Chevrolet','2:Dodge','3:Ford','4:General Motors','5:Nissan','6:Toyota'];

    function init() {

    createOptions('jobs',listJobs);

    createOptions('codes',listCodes);

    createOptions('autos',listCars);

    } init();

    </script>

    </body></html>

    Seems to be a problem with the CSS display section of the above code. Lines between17 to 19 should read:

    input[type=text],

    input [ list ] {

    color: #f0f0f0;

    and :) in listCars should be : ) without the space between characters.
    Copy linkTweet thisAlerts:
    @daveyerwinJul 24.2020 — @sibert#1621240 said ...

    So, there should not be any ad-hoc entering. You must select a existing value.

    ``<i>
    </i>&lt;label for="browser"&gt;Choose your browser from the list:&lt;/label&gt;
    &lt;input list="browsers" name="browser" id="browser"&gt;
    &lt;datalist id="browsers"&gt;
    &lt;option value="Edge"&gt;
    &lt;option value="Firefox"&gt;
    &lt;option value="Chrome"&gt;
    &lt;option value="Opera"&gt;
    &lt;option value="Safari"&gt;
    &lt;/datalist&gt;
    &lt;script&gt;
    browser.onchange=function(){
    for(var i=0;browsers.options.length;++i){
    if (typeof browsers.options[i]=='undefined'){break ;}
    if (browser.value == browsers.options[i].value) break;
    }
    if(i == 5){browser.value = ''}
    }&lt;/script&gt;<i>
    </i>
    ``
    Copy linkTweet thisAlerts:
    @JMRKERJul 24.2020 — It does that by not allowing submission of entries that don't match lists generated to datalist elements.

    The 'Note' entry did not have a list to compare against so there is nothing to compare against, hence: freeformat entry.
    Copy linkTweet thisAlerts:
    @sibertauthorJul 26.2020 — > @JMRKER#1621273 Was that answer not acceptable? Are you trying to do some sort of coder vs. coder comparisons?

    Crossposting is rather common. The reasons may differ. In may case it was to "rephrase" the headline (I could not do this in this forum) in order to make it more clear.

    > I played around with the code and came up with the following.

    > The approach is a bit different from your original post but can be modified as needed if you see the purpose of the suggested changes.


    I do not follow you. Maybe because I am complete newbie to Javascript.

    https://jsfiddle.net/fxbms2n9/4/
    Copy linkTweet thisAlerts:
    @JMRKERJul 27.2020 — @sibert

    For whatever reason, the code I posted (post #2) appears to be garbled and, along with the transfer to your jsfiddle example, has become entirely unusable. The temporal literal created in the alert message is missing the backticks entirely. And there is a space between the $ and { characters which causes an error that produces no output. The beginning / * in the CSS does not seem to display correctly either as it looks like a bullet mark /*. Looks like the same problem I was trying to point out with the interspersed 'happy face' displays.

    I don't know how to use this forum thread to send the correct file contents without re-creating the same errors.

    If you really want to study the code, send me a PM and I'll try to send it directly by email attachment

    (Please don't publish your email address to this forum)

    If I can figure out this forum display problem, I'll try again later.
    Copy linkTweet thisAlerts:
    @sibertauthorJul 27.2020 — > @JMRKER#1621301 I don't know how to use this forum thread to send the correct file contents without re-creating the same errors.

    One way is to edit (or create a new) my existing jsfiddle. Edit and save and copy the new link. I prefer jsfiddle, because it points out my errors and suggests how to fix them (just hover the bullets).
    Copy linkTweet thisAlerts:
    @SempervivumJul 27.2020 — I don't know how to use this forum thread to send the correct file contents without re-creating the same errors.[/quote]Another way is using code tags when posting code:

    `your code here`
    Copy linkTweet thisAlerts:
    @JMRKERJul 28.2020 — @Sempervivum: The way I did it to begin with was by clicking on the </> symbol at the bottom of the 'Post Reply'.

    However, per your suggestion I'll try again, but this time using the [ code] / [ /code] tags.

    <i>
    </i>&lt;!DOCTYPE html&gt;&lt;html lang="en"&gt;&lt;head&gt;&lt;title&gt; Test Page &lt;/title&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;meta name="viewport" content="width-device-width,initial-scale=1.0, user-scalable=yes"/&gt;
    &lt;!--
    From: https://www.sitepoint.com/community/t/validate-data-value-in-a-html-datalist/355469
    And: https://jsfiddle.net/brsf14yu/
    --&gt;
    &lt;link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300"&gt;
    &lt;style&gt;
    /* datalist { display: block; } /* for testing purposes only -- normally display: none */

    * {
    font-family: 'Source Sans Pro', sans-serif;
    font-weight: 300;
    font-size: 18px;
    }
    input[type=text],
    input[list]{
    color: #f0f0f0;
    font-size: 18px;
    padding: 10px;
    max-height: 56px;
    width: 350px;
    background: #555;
    -webkit-appearance: none;
    appearance: none;
    border: none;
    }
    #submit{
    color: #f0f0f0;
    font-size: 18px;
    padding: 10px;
    max-height: 56px;
    width: 370px;
    background: #555;
    -webkit-appearance: none;
    appearance: none;
    border: none;
    }
    &lt;/style&gt;
    &lt;/head&gt;&lt;body&gt;
    &lt;form action="javascript:alert('Success')" method="post"
    onsubmit="return checkInputs()"&gt; &lt;!-- target="_self" --&gt;
    <br/>
    &lt;input id="job" list="jobs" placeholder="Select Job" required="data-value"&gt;
    &lt;datalist id="jobs"&gt;&lt;/datalist&gt;
    &lt;br&gt;
    &lt;input id="code" list="codes" placeholder="Select Code" required="data-value"&gt;
    &lt;datalist id="codes"&gt;&lt;/datalist&gt;
    &lt;br&gt; <br/>
    &lt;input id="note" type="text" placeholder="Note" required&gt;
    &lt;br&gt;
    &lt;input type="submit" value="Submit"&gt; &lt;!-- onsubmit="return checkInputs()" --&gt;
    &lt;br&gt;

    Remove following after testing&lt;br&gt;
    &lt;!-- for testing purposes --&gt;
    &lt;input id="auto" list="autos" placeholder="Car" required="data-value" /&gt;
    &lt;datalist id="autos"&gt;&lt;/datalist&gt;

    &lt;/form&gt;

    &lt;script&gt;
    console.clear();

    function checkInputs() {
    var respJob = document.getElementById('job'),
    respCode = document.getElementById('code'),
    respNote = document.getElementById('note');
    var respCar = document.getElementById('auto'); // for testing purposes only
    const errMsg = 'Please select a valid value';

    var err = 0; // represents no errors
    if (!listJobs.includes(respJob.value)) { err = 1; respJob.setCustomValidity(errMsg); }
    else { respJob.setCustomValidity(''); }
    if (!listCodes.includes(respCode.value)) { err = 2; respCode.setCustomValidity(errMsg); }
    else { respCode.setCustomValidity(''); }
    if (!listCars.includes(respCar.value)) { err = 3; respCar.setCustomValidity(errMsg); }
    else { respCar.setCustomValidity(''); }

    if (err != 0) { // error noted
    alert('Error - invalid entry '+err+' - '+errMsg);
    return false;
    } else { // all OK
    alert(<span><code>${respJob.value}n${respCode.value}n${respNote.value}n${respCar.value}</code></span>);
    return true;
    }
    // return (err !== 0);
    }

    function createOptions(listIDS,Ary) {
    const list = document.getElementById(listIDS);
    Ary.forEach(item =&gt; {
    let option = document.createElement('option');
    // [n,v] = item.split(':'); option.value = item.replace(':',' '); option.textContent = v;
    option.value = item; option.textContent = item;
    list.appendChild(option);
    });
    }

    const listJobs = ['42 Web','43 Print'];
    const listCodes = ['Project Management','COPY'];
    const listCars = ['1:Chevrolet','2:Dodge','3:Ford','4:General Motors','5:Nissan','6:Toyota'];

    function init() {
    createOptions('jobs',listJobs);
    createOptions('codes',listCodes);
    createOptions('autos',listCars);
    } init();
    &lt;/script&gt;

    &lt;/body&gt;&lt;/html&gt;
    Copy linkTweet thisAlerts:
    @daveyerwinJul 28.2020 — @JMRKER#1621334

    &lt;meta name="viewport" content="width-device-width,initial-scale=1.0, user-scalable=yes"/&gt;

    should be

    &lt;meta name="viewport" content="width=device-width,initial-scale=1.0, user-scalable=yes"/&gt;
    Copy linkTweet thisAlerts:
    @JMRKERJul 28.2020 — My eyes must be getting old ... I don't see the difference. 😕

    Ah. Just spotted the '=' instead of '-'. Well spotted. Helps to use a bigger font! :)
    Copy linkTweet thisAlerts:
    @daveyerwinJul 28.2020 — @sibert#1621240 said ...

    The value selected in the datalist should be verified by a "data-value".

    So, there should not be any ad-hoc entering. You must select a existing value.


    entered data case sensitive

    must capitalize first letter
    ``<i>
    </i>&lt;form onsubmit='return val(false)'&gt;
    &lt;label for=browser&gt;Choose your browser from the list:&lt;/label&gt;
    &lt;input list=browsers name=browser id=browser data-noadhoc&gt;
    &lt;datalist id=browsers&gt;
    &lt;option data-id=1 value="Edge"&gt;
    &lt;option data-id=2 value="Firefox"&gt;
    &lt;option data-id=3 value="Chrome"&gt;
    &lt;option data-id=4 value="Opera"&gt;
    &lt;option data-id=5 value="Safari"&gt;
    &lt;/datalist&gt;
    &lt;button&gt;Send&lt;/button&gt;
    &lt;/form&gt;
    &lt;script&gt;
    window.oninput=function(e){
    if(e.target.dataset.noadhoc == undefined)return;
    var list=e.target.list;
    (function chek(ok){
    for(var i=0;i&lt;list.options.length;++i)
    if (e.target.value == list.options[i].value.substring(0,e.target.value.length))ok=true;
    if(!ok){e.target.value = e.target.value.substring(0,e.target.value.length-1);chek();}}
    )(false);
    }
    function val(ok){
    for(var i=0;i&lt;browsers.options.length;i++)
    if(browsers.options[i].value == browser.value){
    ok=true;browser.value=browsers.options[i].dataset.id;}
    if(!ok) alert('Failed');
    return ok;
    }
    &lt;/script&gt;<i>
    </i>
    ``

    the function that prohibits adhoc letters will work

    on any datalist on page if the input element has

    the data-noadhoc attribute
    ×

    Success!

    Help @sibert spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 4.18,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,

    tipper: @Samric24,
    tipped: article
    amount: 1000 SATS,
    )...