简体   繁体   中英

How do I customize <select> display value?

I have a simple select:

<select>
    <option value="1" displayvalue="text 1">Very very long text 1</option>
    <option value="2" displayvalue="text 1">Very very long text 2</option>
    <option value="3" displayvalue="text 1">Very very long text 3</option>
</select>

When the select dropdown opens, you see the "Very very long text" as you normally should.

But, whenever I choose an option, and the dropdown closes, I want the displayvalue attribute to display in the select box instead of option's inner text (ie "text1" ).

What I am looking for is a something like:

option.onchange = function(){
    this.text = this.selectedOption.getAttribute("displayvalue");
}

I also can't seem to be able to find an option property that allows me to change the displayed text only, and not it's actual value.

Target the selected option using selectedindex

 function gettext(sel) { alert(sel.options[sel.selectedIndex].getAttribute('displayvalue')); }
 <select onchange="gettext(this)"> <option value="1" displayvalue="text 1">Very very long text 1</option> <option value="2" displayvalue="text 1" selected>Very very long text 2</option> <option value="3" displayvalue="text 1">Very very long text 3</option> </select>

Using Dom listener

 $elem = document.querySelector('select') $elem.addEventListener('change', gettext) function gettext() { console.log(this.options[this.selectedIndex].getAttribute('displayvalue')); }
 <select> <option value="1" displayvalue="text 1">Very very long text 1</option> <option value="2" displayvalue="text 2" selected>Very very long text 2</option> <option value="3" displayvalue="text 3">Very very long text 3</option> </select>

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