1

I'm new to jQuery selectize and I'm having issues in setting the value to a <select> from database during editing the form. The <option> is hardcoded in HTML.

HTML:

<select class="form-control" name="agentType" id="agentType">
    <option value="">--Select Agent Type--</option>
    <option value="Individual">Individual</option>
    <option value="Partner">Partner</option>
</select>

Let's say the two values are saved in database viz(Individual & Partner).

database

And when I hit edit, I want one of Agent Type to be pre-selected and other one in the drop-down corresponding to value saved in database. Images shown Shown below:

beforeAfter

Jquery:

$('#agentDataTable tbody').on( 'click', '.dataEdit', function () {
    var data = agentDataTable.row( $(this).parents('tr') ).data();

    $('#agentForm #agentName').val(data.agentName);
    var $select = $('#agentForm #agentType').selectize();
    var control = $select[0].selectize;
    control.clear();
    control.clearOptions();
    control.addOption({text: data.agentType});
    control.setValue(data.areaPincodeId, true);
    });

But nothing shows at all in dropdown.

I've tried many other references but no answer matched my query as everyperson has their own ways.

java-user
  • 271
  • 4
  • 16

1 Answers1

2

selectize is a plugin on jQuery provided on GitHub as far as I know,

In your question you didn't showed the method where you are making the select field selectize and by seeing your query my guess is that you didn't wrote that method properly and you're missing id: data.agentType in your datatable's method.

I'm providing you a method to do selectize to select field and datatable's query to fetch it.

Replace the below method in your jquery file for selectize.

function setAgentTypeSelect() {
    var $agentTypeSelect = $('#agentForm #agentType').selectize({
        selectOnTab: true,
        closeAfterSelect: true,
        persist: true,
        valueField: 'id',
        labelField: 'text',
        options: [],
        preload: true,
        create: false
    }); 
}

And in your datatable method just replace your addOptions control.addOption({id: data.agentType, text: data.agentType});

I'm sure that by changing these things will get what you wanted to do.

Cybertronian
  • 473
  • 1
  • 8
  • 17