SaltProgrammer
SaltProgrammer

Reputation: 1055

Select All / DeSelect All Options in jQuery Mobile

I'm trying to do a select all, deselect all with jQuery Mobile. It seems trivial, but been pulling my hear out all day about this. This is what it looks like:

Here's the JSFiddle.

enter image description here

<div data-role="page" id="one">
  <div data-role="content">
    <label for="sel">Select the Options</label>
    <select name="sel" id="sel" data-native-menu="false" multiple="multiple">
      <option value="-1" selected>-All Brands-</option>
      <option value="1">Prod 1</option>
      <option value="2">Prod 2</option>
      <option value="3">Prod 3</option>
    </select>
  </div>
</div>

JavaScript:

var arr = [];
$("#sel").live("change", function (event, ui) {
    var txt = $("#sel option:selected").text();
    if (txt.search("-All Brands-")) {

        $("#sel option").attr("selected", "selected");

    }
    else {
        $("#sel option:selected").removeAttr("selected");

    }
    $("#sel").selectmenu("refresh", true);
})

I've tried a bunch of stuff and can't get it just right.

Upvotes: 2

Views: 2134

Answers (2)

&#214;zkan Azazi
&#214;zkan Azazi

Reputation: 91

If you choose to manipulate the classes you can do it manually like this:

// For de-selecting

$( '#yourSelectMenuId'  ).val( '' ).change();
$( '#yourSelectMenuId-listbox ul li a' ).removeClass( 'ui-checkbox-on' );
$( '#yourSelectMenuId-listbox ul li a' ).addClass( 'ui-checkbox-off' );

don't forget adding -listbox extension to your select menu id which jqm added automatically.

Upvotes: 0

Damon Smith
Damon Smith

Reputation: 1790

Ok the jquery mobile multi select only has a change event, as you probably read. So the only way I can think of is to store the state of the all brands item and then check if it's changed, and select or deselect all. Here's your JSFiddle with the changes:

http://jsfiddle.net/Gm89P/7/

like this:

var arr = [];
$("#sel").on("change", function (event, ui) {

    var allSelected = $("option:first", this).attr("selected");

    if (this.wasAllSelected && !allSelected) {
        $("#sel option:selected").removeAttr("selected");
        this.wasAllSelected = allSelected;
    }
    else if (!this.wasAllSelected && allSelected) {
        $("#sel option").attr("selected", "selected");
        this.wasAllSelected = allSelected;
    }
    $("#sel").selectmenu("refresh", true);
})

Upvotes: 1

Related Questions