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

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

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

android - How to create dynamically Fragment pager adapter -