vicb/bsmSelect

After create new option, the order doesn't is kept

intropedro opened this issue · 6 comments

I have this select:

<select id="myselect" name="test" multiple="multiple">
    <option value="40">A</option>
    <option value="75">B</option>
    <option value="41">C</option>
    <option selected="selected" data-bsm-order="1" value="29">D</option>
    <option value="39">E</option>
    <option value="23">F</option>
    <option selected="selected" data-bsm-order="0" value="44">G</option>
    <option value="62">H</option>
    <option value="38">I</option>
    <option value="61">J</option>
</select>

And the Javascript:

jQuery("#myselect").bsmSelect({
    addItemTarget: 'original',
    plugins: [jQuery.bsmSelect.plugins.sortable(), jQuery.bsmSelect.plugins.compatibility()]
});

The select is showed in the correct order. Then I change the order and after I add an option:

var option = jQuery("<option>", { text: 'NEW', selected: "selected"});
    jQuery("#myselect").append(option).change();

But the order of the options is changed to the initial and not to the last order.

I have tried update the attribute 'data-bsm-order' to the current order but it doesn't work:

jQuery("#myselect option[selected=selected]").each(function(i, option) {
jQuery(option).attr( "data-bsm-order", i);
});
vicb commented

it would really help if you can come with a runnable example (ie a plunker) and describe the observed vs desired behavior. Thanks.

This is one example: https://jsfiddle.net/vj13191t/3/

At the beginning:

  • 1- G
  • 2- D

Move D to 1:

  • 1- D
  • 2- G

Add X from the input and the result is:

  • 1- G
  • 2- D
  • 3-X

But I think it would be so:

  • 1- D
  • 2- G
  • 3- X
vicb commented

Thanks for the fiddle.

The problem is that the sortable plugin does not update the the data-bsm-order when an option is added or when the list is re-ordered.

One solution would be to update the plugin (onChange and onSort) to set or update this order.

An other solution would be to use: addItemTarget: 'bottom' and render the option in the desired order in the original select.

I've also tried updating parameters "data-bsm-order" before adding the new option , but did not work:

jQuery("#add_button").click(function() {
    jQuery("#myselect option[selected=selected]").each(function(i, option) {
         jQuery(option).attr( "data-bsm-order", i);
    });
    ....
});
vicb commented

You should try to do it in the sortable plugin and probably want to do jQuery(option).data('bsm-order', i)