Search code examples
jquerydropdownbox

How to truncate only selected text of dropdown using jquery


I have a dropdown

<div>
<select id="ddlTruncate">
    <option selected="selected">Select </option>       
    <option value="1">tetetetetetetet </option>
    <option value="2">tetetetetetetetetetete </option>
    <option value="3">tetetetetettetete </option>        
</select>
</div>

I want to truncate only the selected value and if the value gets change in previous value should show the original value

 $('#ddlTruncate').change(function () {
     var textval = $('#ddlTruncate :selected').text(); 
     var ddlval= $(this).val();   
        if(textval.length > 5) {    
            $('#ddlTruncate :selected').text(textval.substr(0,4)+'…');
        }
 });

Currently when I am selected any other option then previous value is show refracting to original value. Please check the link http://jsfiddle.net/hurera1111/6x039o7w/


Solution

  • Updated fiddle here for you.

    Store the actual text in the data-text for the option, then on change, change the text of all the options but not the :selected one.