Get selected item value from select2 dynamically created item in code behind

Viewed 50

I'm using bootstrap select2 control with dynamic item creation

function pageLoad(sender, args) {
  $('select').select2({
    tags: true
  });

  $("#btn-add-state").on("click", function() {
    var newStateVal = $("#new-state").val();
    // Set the value, creating a new option if necessary
    if ($('select').find("option[value='" + newStateVal + "']").length) {
      $('select').val(newStateVal).trigger("change");
    } else {
      // Create the DOM option that is pre-selected by default
      var newState = new Option(newStateVal, newStateVal, true, true);
      // Append it to the select
      $('select').append(newState).trigger('change');
    }
  });
}

I tried this get value but it always returns null!

cmd.Parameters.AddWithValue("@company", txt_car_company.Value);

I also tried to set the value in an ASP hidden field but it also returned null

<select id="txt_car_company" runat="server" class="select-single select2-hidden-accessible" data-live-search="true" data-select2-id="txt_car_company" aria-hidden="true" required="required">
  <option value="Audi">Audi</option>
</select>
<asp:HiddenField ID="hcarcompany" runat="server" />
<script>
  $('#txt_car_company').on('change', function () {
    $('#<%=hcarcompany.ClientID%>').val($(this).val());
  }
</script>
0 Answers
Related