Home > Mobile >  how can I get attributes of selected option of datalist on input tag
how can I get attributes of selected option of datalist on input tag

Time:01-06

I have the following html

Area: <input onchange="loadInfo()" id="area_input" list="areas" placeholder="choose option: ">
<datalist id="areas" >
        <option abrv="TV"> TV </option>
        <option abrv="NOT"> NOTEBOOK </option>
        <option abrv="ARC"> AIR CONDITIONING </option>
        <option abrv="PIN"> PINS </option>
</datalist>

I learned that when the user selects an option, I can get its value via Javascript doing

document.getElementById('area_input').value

My objective is to get the 'abrv' attribute, however I noticed it does not get carried to input tag.

How can I get attributes from the selected option via JS?

P.S. (my intention is to use it to append to a DJANGO url 'database/area/[abrv]' and even if on this specific case I can do some work-around striping the value string, on the future I will need to get codes from strings)

I tried this solution: enter image description here FROM tried_solution result the resulting code was like this

`<datalist id="areas">
 
        <option value="IMC">IMC</option>
    
        <option value="INJ">INJEÇÃO PLÁSTICA</option>
    
        <option value="NOT">NOTEBOOK</option>
    
        <option value="TRA">TRANSFORMADOR</option>
    
        <option value="TV">TV</option>
    
</datalist>`

the solution told me user would see only what was inside the tag, but on cases where the attribute value was different than the actual value inside the tag it showed the user both info, I wanted to show only the full text to the user

CodePudding user response:

You can store extra information in data-* attributes. Then search options list for match by input's value:

HTML

<input onchange="loadInfo()" id="iareas" list="areas" placeholder="choose option: ">
    <datalist id="areas" >
        <option data-value="TV">TV</option>
        <option data-value="NOT">NOTEBOOK</option>
        <option data-value="ARC">AIR CONDITIONING</option>
        <option data-value="PIN">PINS</option>
    </datalist>

SCRIPT

function loadInfo() {
        const data = document.getElementById("areas");
        const opts  = data.options;

        const v = document.getElementById("iareas").value;
        for(let i=0; i<opts.length; i  ) {
            const o = opts[i];
            if(o.text === v) {
                console.log(o.getAttribute("data-value")); //do anything with value
                break;
            }
        }

    }
  • Related