Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML select shows value instead of text

Is it possible in a html select, to display the value of the option instead of the text?

It's gonna be used for displaying a long disription in the dropdown, but when selecting it should only be showing a short text/ the value of the option.

code:

<select>
    <option value="1">This is a long long text, that explains option 1</option>
    <option value="2">This is a long long text, that explains option 2</option>
</select>

Now the selected item, when you leave the dropdown/combobox/whatever, should only display '1'

like image 497
AP87 Avatar asked Feb 11 '14 10:02

AP87


People also ask

How do I change selection options in HTML?

We can change the HTML select element's selected option with JavaScript by setting the value property of the select element object. We have a select drop down with some options and 2 buttons that sets the selected options when clicked. We get the 2 buttons with getElementById .

Does select tag have value?

select elements do not have a value attribute.

What does it mean when the value of the selected menu option is an empty string?

</option> , value="" is turned into just value . The value, when set to the empty string is simply discarded.

What is value in select HTML?

The value attribute specifies the value to be sent to a server when a form is submitted. The content between the opening <option> and closing </option> tags is what the browsers will display in a drop-down list. However, the value of the value attribute is what will be sent to the server when a form is submitted.


Video Answer


2 Answers

You can do it by using the label tag:

<option value="the_value" label="the text displayed">the hidden text</option>
like image 82
Fernán García de Zúñiga Avatar answered Sep 19 '22 08:09

Fernán García de Zúñiga


This is the solution.

$("select option").each(function () {
    $(this).attr("data-label", $(this).text());
});
$("select").on("focus", function () {
    $(this).find("option").each(function () {
        $(this).text($(this).attr("data-label"));
    });
}).on("change mouseleave", function () {
    $(this).focus();
    $(this).find("option:selected").text($(this).val());
    $(this).blur();
}).change();
like image 21
Jeffrey Neo Avatar answered Sep 20 '22 08:09

Jeffrey Neo