How To Show Different Selected Value Than Options Label
I have simple html select:
Solution 1:
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>
Post a Comment for "How To Show Different Selected Value Than Options Label"