javascriptjqueryappenddropdownpostback

jQuery appends dropdownlist, but appended item disappears on postback


I'm appending items to a dropdownlist using jQuery. Values are coming from a textbox on my page. Here's the code I'm using:

$('#ddlProjectName').append( new Option($('#txtNewProjectName').val(), $('#txtNewProjectName').val()));
$('#ddlProjectName').val($('#txtNewProjectName').val());    //  select appended item

This seems to work fine; I can see the new item in my dropdown list, and it is the currently selected item. But when I select a different item in the dropdown list, my newly-appended item is no longer there. The c# in my code behind can't see it either.

The problem is that my dropdownlist is auto-posting back (to fire my code behind when my user makes a selection). This is what's clearing the appended item, but I don't know what to do about it.

I also tried:

$('#ddlProjectName').val($('#txtNewProjectName').val()).trigger('change');

No luck there. I've looked around this site and I really thought that this post would get me somewhere, but I don't understand the answer.

Any thoughts are appreciated.


Solution

  • As you described your dropdown is updated after selecting. So...
    An optimal way would be to debug step-by-step and find where you dropdown updated and call your option adding code after that event.
    If you have no control over it or you want to be agnostic (your code doesn't care what updates your dropdown) use MutationObserver to watch your dropdown for updates.

    // code you don't control
    
    const fillSelect = () => 'name1 name2 name3'.split(' ').forEach(
      text => $('<option>', {value: text, text}).appendTo('select')
    );
    
    // this erases the options and fills them again thus destroying your extra options
    $('select').on('change', () => $('select').empty() + fillSelect() + console.log('cleared by 3rd party'));
    
    fillSelect();
    
    // code you control
    
    const appendSelect = () => {
    
      'append1 append2 append3'.split(' ').forEach(
        text => $('<option>', {value: text, text}).appendTo('select')
      );
      
      $('select').val('append3');
      console.log('appended extra options and set value');
    };
    
    appendSelect();
    
    const observer = new MutationObserver(() => observer.disconnect() + appendSelect() + observe());
    
    const observe = () => observer.observe($('select')[0], { childList: true });
    
    observe();
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <select></select>