AP87
AP87

Reputation: 521

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'

Upvotes: 18

Views: 48031

Answers (5)

Jeffrey Neo
Jeffrey Neo

Reputation: 3809

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();

Upvotes: 2

You can do it by using the label tag:

<option value="the_value" label="the text displayed">the hidden text</option>

Upvotes: 13

I found a solution that might solve your problem:

HTML:

<select id="countryCode">
   <option data-text="his is a long long text, that explains option 1" value="1">This is a long long text, that explains option 1</option>
   <option data-text="his is a long long text, that explains option 1" value="2">This is a long long text, that explains option 1</option>
</select>

jQuery:

$('#countryCode option:selected').html($('#countryCode option:selected').attr('value')); // already changed onload

$('#countryCode').on('change mouseleave', function(){
    $('#countryCode option').each(function(){
      $(this).html( $(this).attr('data-text') ); 
    });
    $('#countryCode option:selected').html(  $('#countryCode option:selected').attr('value')   );
    $(this).blur();
});
$('#countryCode').on('focus', function(){
    $('#countryCode option').each(function(){
        $(this).html( $(this).attr('data-text') ); 
    });
});

http://jsfiddle.net/9y43gh4x/

Upvotes: 1

Myth
Myth

Reputation: 446

I think This may help you

<select id='cboSelect'>
 <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>

Try this jquery

$("#cboSelect").change(function(){    
   $("#cboSelect option:selected").text($("#cboSelect").val());
});

this will change the text of the selected option with its corresponding value

Here is the fiddle Fiddle

Upvotes: 0

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174957

Just don't give a value:

<select>
    <option>Test</option>
</select>

Will submit Test when selected.

Just place the values you put in value as the text.

You can't have it show the value in value= just like that.

Upvotes: -1

Related Questions