Peter Dub
Peter Dub

Reputation: 531

How to show different selected value than options label

I have simple html select:

<select id="mySelect" style="width:10em">
  <option value="val1">Some long text for val 1</option>
  <option value="val2">Some long text for val 2</option>
  <option value="val3">Some long text for val 3</option>
</select>

opened combo box:

opened combo box

I dont see what I've selected, I don't want to set width, I want to show different text.

selected combobox

I want to keep those long texts in floating panel, but when option is selected, I want to see some short version to see option in small space.Is there any solution to show different text in closed than in opened mode?

Upvotes: 0

Views: 3516

Answers (1)

Peter Dub
Peter Dub

Reputation: 531

I solved this problem using jQuery by adding hidden option that decouples selected value and text. Just override that this hidden option will be selected always and update its value to whatever you want. In this case I used value as text, but it can be stored in some custom a

var val = $("#mySelect").val();
var lbl = $("#mySelect option:selected").text();
$("#mySelect").prepend("<option value='" + val + "' data-value='selected' selected hidden>" + val + "</option>");

$("#mySelect").on('change', function() {
	var val = $("#mySelect").val();
  var lbl = $("#mySelect option:selected").text();
  
  $("#mySelect option[data-value='selected']").attr('value', val);
  $("#mySelect option[data-value='selected']").text(val);
  
  $("#mySelect").val(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2>
jQuery hidden option
</h2>
<select id="mySelect" style="width:10em">
  <option value="val1">Some long text for val 1</option>
  <option value="val2">Some long text for val 2</option>
  <option value="val3">Some long text for val 3</option>
</select>

Other approach is use bootstrap-select like in example:

<select class="selectpicker">
  <option title="Combo 1">Hot Dog, Fries and a Soda</option>
  <option title="Combo 2">Burger, Shake and a Smile</option>
  <option title="Combo 3">Sugar, Spice and all things nice</option>
</select>

Upvotes: 1

Related Questions