简体   繁体   中英

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

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?

PS (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: 在此处输入图像描述 FROM Get Id of selected item in datalist

it ended up showing things in a weird way尝试过的解决方案结果 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

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;
            }
        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM