javascript - Change selected text of a dropdown without changing the text in the option? -


how change selected text of dropdown without changing text in option? ex: if dropdown has code , description both on select wants display code , remove description description should present in dropdown.

populating data in dropdown:

$.each(jtc12_2_2_reasoncode1list, function(i, item) {             $('#jtc12_2_reasonforfailure1').append($('<option>', {                 value : item.code,                 text : item.code + " " + item.description             }));         }); 

change text of selected option:

 var jtc12_2_2_reasoncode1code = $("#jtc12_2_reasonforfailure1 :selected").val();         var jtc12_2_2_reasoncode1desc = _.filter(e.data.jtc12_2_2_reasoncode1list, function(item) {             return item.code === jtc12_2_2_reasoncode1code;         });         jtc12_2_2_reasoncode1desc = jtc12_2_2_reasoncode1desc[0].description;         $("#jtc12_2_reasonforfailure1 option[value = " + jtc12_2_2_reasoncode1code + "]").text(jtc12_2_2_reasoncode1code); 

one way achieve add new option @ runtime , select (the newly added) value instead of selected value. selected value can removed on dropdown's click event.

assuming code , description separated colon (:) refer following code.

var onselect = false; $('select').click(function (e) {       if ($(this).val() !== '' && !onselect) {         $(this).find('option:selected').remove();     } else {          onselect = false;     } });  $('select').change(function (e) {      var selectedval = $(this).val();     var newval = selectedval.split(':')[0];     $(this).append($('<option>', {         value: newval,         text: newval     }));      $(this).val(newval);     $(this).find('option:selected').hide();     onselect = true; }); 

jsfiddle


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -