jQuery mobile Multiselect doesn't update selected attribute

1.1k views Asked by At

I have a jQuery mobile custom multiselect, but when I select one item we have the list of items on the HTML select tag, but it is not updated with the selected attribute.

Using the Multiple selects example of the page:

<div data-role="fieldcontain" class="ui-field-contain ui-body ui-br">
  <label for="select-choice-9" class="select ui-select">
    Choose shipping method(s):
  </label>
  <div class="ui-select">
    <a href="#" role="button" aria-haspopup="true" data-theme="c" class="ui-btn ui-btn-icon-right ui-btn-corner-all ui-shadow ui-btn-up-c">
      <span class="ui-btn-inner ui-btn-corner-all">
        <span class="ui-btn-text">
          Rush: 3 days, Express: next day
        </span>
        <span class="ui-icon ui-icon-arrow-d ui-icon-shadow"></span>
      </span>
      <span class="ui-li-count ui-btn-up-c ui-btn-corner-all" style="">
        2
      </span>
    </a>

    <select name="select-choice-9" id="select-choice-9" multiple="multiple" data-native-menu="false" tabindex="-1">
      <option>Choose options</option>
      <option value="standard">Standard: 7 day</option>
      <option value="rush">Rush: 3 days</option>
      <option value="express">Express: next day</option>
      <option value="overnight">Overnight</option>
    </select>
  </div>
</div>

Is there a way for making it add the selected attribute by default ?

1

There are 1 answers

0
devconcept On BEST ANSWER

JQuery Mobile by default will not update the selected attribute in response to the user's input. You can keep the selected values in sync with the attributes with the following code.

$(function () {
    $('select').on('change', function (evt) {
        var options = $(evt.target).children('option'),
            current;
        for (var i = 0; i < options.length; i++) {
            current = options[i];
            if (current.selected === true && !current.hasAttribute('selected')) {
                options[i].setAttribute('selected', '');
            }
            if (current.selected === false && current.hasAttribute('selected')) {
                options[i].removeAttribute('selected');
            }
        }
    });
});

Remember that this will work for all the selectmenu widgets that you already have in the DOM. If you add one programmatically you also have to add the event handler to that widget.