JQM Change Select icon to Notext - jquery-mobile

In trying to keep website responsive I want to hide the text from a select menu when the screen is below a certain size.
I use something similar to remove button text.
function resizeBtn() {
var activePage = $.mobile.pageContainer.pagecontainer("getActivePage");
if ($(window).width() <= 490) {
$("#opt_user_btn.ui-btn-icon-left", activePage).toggleClass("ui-btn-icon-notext ui-btn-icon-left");
$( "#storeselect", activePage ).selectmenu( "option", "iconpos", "notext" );
} else {
$("#opt_user_btn.ui-btn-icon-notext", activePage).toggleClass("ui-btn-icon-left ui-btn-icon-notext");
$( "#storeselect", activePage ).selectmenu( "option", "iconpos", "notext" );
}
}
And the html is along the lines of:
<form><select name="storeselect" id="storeselect" data-native-menu="true" data-iconpos="left" onChange="this.form.submit();" >
<option value="1">1</option>
<option value="2">2</option>
</select>
</form>
I've looked at JQM info but not figured it out yet. Help would be appreciated. Thank you. :)

Inspecting the select bar the text for the selected option is in a span tag. One solution is to add a class with opacity:0 to the span
<div id="storeselect-button" class="ui-btn ui-icon-carat-d ui-btn-icon-left ui-corner-all ui-shadow"><span>Option 1</span><select name="storeselect" id="storeselect" data-native-menu="true" data-iconpos="left">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select></div>
Demo
http://jsfiddle.net/mjk0f0t7/
Jquery
$(window).on('resize change', function () {
if ($(window).width() <= 490) {
$("#storeselect-button").find("span").addClass("noshow")
} else {
$("#storeselect-button").find("span").removeClass("noshow");
}
});
Css
.noshow {
opacity:0;
}
To hide or style the icon also
$("#storeselect").append('<style>.ui-btn-icon-left:after{opacity:0}</style>');
Demo
http://jsfiddle.net/wuLccyda/
To add ui-btn-icon-notext class simply use addClass and refresh the select menu
$(window).on('resize', function () {
if ($(window).width() <= 490) {
$("#storeselect").addClass("ui-btn-icon-notext")
$('#storeselect').selectmenu('refresh', true);
} else {
$("#storeselect").removeClass("ui-btn-icon-notext")
$('#storeselect').selectmenu('refresh', true);
}
});
Demo
http://jsfiddle.net/ywp70xtc/

Related

Select2 with tags set to true: Is it possible to always keep the placeholder after selecting the options?

I want the placeholder to be shown always whether the option is added, selected, or removed. Currently, the placeholder shows after removing the options or after adding the new options. But when the option is selected from the dropdown the placeholder will disappear. This may be the original functionality of the seelct2 plugin. Is there any way to keep the placeholder always visible?
$("select.add-tags").select2({
tags: true,
dropdownParent: $(".select-tags"),
placeholder: "Start typing the tag name..."
});
if ($("select.add-tags").select2("data").length) {
$("select.add-tags")
.next()
.find(".select2-search.select2-search--inline .select2-search__field")
.attr("placeholder", "Placeholder on default");
$("select.add-tags")
.next()
.find(".select2-search.select2-search--inline .select2-search__field")
.css("width", "200px");
}
$("select.add-tags").on("select2:select", function (evt) {
// console.log($(this).val());
console.log("select2 : select");
var element = evt.params.data.element;
var $element = $(element);
$element.detach();
$(this).append($element);
$(this).trigger("change");
if (
$(".select2-search.select2-search--inline .select2-search__field").is(
":focus"
)
) {
console.log("tag input fpcused");
$(".select2-search.select2-search--inline").removeAttr("style");
$(
".select2-search.select2-search--inline .select2-search__field"
).removeAttr("style");
$(".select2-search.select2-search--inline .select2-search__field").attr(
"placeholder",
"Placeholder on select"
);
$(".select2-search.select2-search--inline .select2-search__field").css(
"width",
"200px"
);
}
});
$("select.add-tags").on("select2:unselect", function () {
console.log($(this).val());
console.log("select2 : unselect");
if ($("select.add-tags").val().length == 0) {
$(".select2-search.select2-search--inline .select2-search__field").attr(
"placeholder",
"Start typing the tag name..."
);
$(".select2-search.select2-search--inline .select2-search__field").css(
"width",
"100%"
);
$(".select2-search.select2-search--.select2-search__field").css(
"width",
"100%"
);
} else {
$(".select2-search.select2-search--inline .select2-search__field").attr(
"placeholder",
"Add another tag"
);
$(".select2-search.select2-search--inline .select2-search__field").css(
"width",
"200px"
);
$(".select2-search.select2-search--inline").removeAttr("style");
}
});
select {
width: 300px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2-bootstrap-css/1.4.6/select2-bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/css/select2.min.css rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js"></script>
<div class="container select-tags">
<select class="add-tags error" multiple="multiple">
<option value="Red">Red</option>
<option value="Yellow">Yellow</option>
<option value="Green">Green</option>
<option value="Blue" selected>Blue</option>
<option value="Pink">Pink</option>
<option value="Black">Black</option>
</select>
</div>
Codepen: https://codepen.io/jagruti23/pen/bGggJZR

Jquery Mobile Filterable Select Long List

I'm trying to create a custom select menu with filter like on the demo page:
http://demos.jquerymobile.com/1.4.5/selectmenu-custom-filter/
It works fine for short list:
http://jsfiddle.net/dw1c1439/
But it's not working for long lists:
https://jsfiddle.net/pppzLbfu/
I keep getting the error:
SCRIPT5007: Unable to get property 'jqmData' of undefined or null reference
My full code is
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Filterable inside custom select - jQuery Mobile Demos</title>
<link rel="shortcut icon" href="../favicon.ico">
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:300,400,700">
<link rel="stylesheet" href="jquery.mobile/css/themes/default/jquery.mobile-1.4.5.min.css">
<link rel="stylesheet" href="jquery.mobile/_assets/css/jqm-demos.css">
<script src="jquery.mobile/js/jquery.js"></script>
<script src="jquery.mobile/_assets/js/index.js"></script>
<script src="jquery.mobile/js/jquery.mobile-1.4.5.min.js"></script>
<script>
( function( $ ) {
function pageIsSelectmenuDialog( page ) {
var isDialog = false,
id = page && page.attr( "id" );
$( ".filterable-select" ).each( function() {
if ( $( this ).attr( "id" ) + "-dialog" === id ) {
isDialog = true;
return false;
}
});
return isDialog;
}
$.mobile.document
// Upon creation of the select menu, we want to make use of the fact that the ID of the
// listview it generates starts with the ID of the select menu itself, plus the suffix "-menu".
// We retrieve the listview and insert a search input before it.
.on( "selectmenucreate", ".filterable-select", function( event ) {
var input,
selectmenu = $( event.target ),
list = $( "#" + selectmenu.attr( "id" ) + "-menu" ),
form = list.jqmData( "filter-form" );
// We store the generated form in a variable attached to the popup so we avoid creating a
// second form/input field when the listview is destroyed/rebuilt during a refresh.
if ( !form ) {
input = $( "<input data-type='search'></input>" );
form = $( "<form></form>" ).append( input );
input.textinput();
list
.before( form )
.jqmData( "filter-form", form ) ;
form.jqmData( "listview", list );
}
// Instantiate a filterable widget on the newly created selectmenu widget and indicate that
// the generated input form element is to be used for the filtering.
selectmenu
.filterable({
input: input,
children: "> option[value]"
})
// Rebuild the custom select menu's list items to reflect the results of the filtering
// done on the select menu.
.on( "filterablefilter", function() {
selectmenu.selectmenu( "refresh" );
});
})
// The custom select list may show up as either a popup or a dialog, depending on how much
// vertical room there is on the screen. If it shows up as a dialog, then the form containing
// the filter input field must be transferred to the dialog so that the user can continue to
// use it for filtering list items.
.on( "pagecontainerbeforeshow", function( event, data ) {
var listview, form;
// We only handle the appearance of a dialog generated by a filterable selectmenu
if ( !pageIsSelectmenuDialog( data.toPage ) ) {
return;
}
listview = data.toPage.find( "ul" );
form = listview.jqmData( "filter-form" );
// Attach a reference to the listview as a data item to the dialog, because during the
// pagecontainerhide handler below the selectmenu widget will already have returned the
// listview to the popup, so we won't be able to find it inside the dialog with a selector.
data.toPage.jqmData( "listview", listview );
// Place the form before the listview in the dialog.
listview.before( form );
})
// After the dialog is closed, the form containing the filter input is returned to the popup.
.on( "pagecontainerhide", function( event, data ) {
var listview, form;
// We only handle the disappearance of a dialog generated by a filterable selectmenu
if ( !pageIsSelectmenuDialog( data.toPage ) ) {
return;
}
listview = data.prevPage.jqmData( "listview" ),
form = listview.jqmData( "filter-form" );
// Put the form back in the popup. It goes ahead of the listview.
listview.before( form );
});
})( jQuery );
</script>
<style>
.ui-selectmenu.ui-popup .ui-input-search {
margin-left: .5em;
margin-right: .5em;
}
.ui-selectmenu.ui-dialog .ui-content {
padding-top: 0;
}
.ui-selectmenu.ui-dialog .ui-selectmenu-list {
margin-top: 0;
}
.ui-selectmenu.ui-popup .ui-selectmenu-list li.ui-first-child .ui-btn {
border-top-width: 1px;
-webkit-border-radius: 0;
border-radius: 0;
}
.ui-selectmenu.ui-dialog .ui-header {
border-bottom-width: 1px;
}
</style>
</head>
<body>
<div data-role="page" class="jqm-demos" id="pageMainForm">
<div data-role="header" class="jqm-header">
<h2><img src="../_assets/img/jquery-logo.png" alt="jQuery Mobile"></h2>
<p>Demos <span class="jqm-version"></span></p>
Menu
Search
</div><!-- /header -->
<div data-role="content" class="ui-content jqm-content">
<h1>Filterable inside custom select</h1>
<div data-demo-html="true" data-demo-js="true" data-demo-css="true">
<form>
<select id="filter-menu" class="filterable-select" data-native-menu="false">
<option value="Option 1">Option 1</option>
<option value="Option 2">Option 2</option>
<option value="Option 3">Option 3</option>
<option value="Option 4">Option 4</option>
<option value="Option 5">Option 5</option>
<option value="Option 6">Option 6</option>
<option value="Option 7">Option 7</option>
<option value="Option 8">Option 8</option>
<option value="Option 9">Option 9</option>
<option value="Option 10">Option 10</option>
<option value="Option 11">Option 11</option>
<option value="Option 12">Option 12</option>
<option value="Option 13">Option 13</option>
<option value="Option 14">Option 14</option>
<option value="Option 15">Option 15</option>
<option value="Option 16">Option 16</option>
<option value="Option 17">Option 17</option>
<option value="Option 18">Option 18</option>
<option value="Option 19">Option 19</option>
<option value="Option 20">Option 20</option>
<option value="Option 21">Option 21</option>
<option value="Option 22">Option 22</option>
</select>
</form>
</div>
</div><!-- /content -->
</div><!-- /page -->
</body>
</html>
Here's the solution if you still need it:
The demo itself has some errors. Here is a way to do it:
// demo-dialog is ID of selectmenu (demo) + (-dialog) which is added
// by jQM dynamically upon creating a custom selectmenu
$(document).on("pagecreate", "#demo-dialog", function (e) {
var form = $("<form><input data-type='search'/></form>"),
page = $(this);
$(".ui-content", this)
.prepend(form);
form.enhanceWithin()
.on("keyup", "input", function () {
var data = $(this).val().toLowerCase();
$("li", page).addClass("ui-screen-hidden")
.filter(function (i, v) {
return $(this).text().toLowerCase().indexOf(data) > -1;
}).removeClass("ui-screen-hidden");
});
$(document).on("pagecontainerhide", function () {
$("#demo-menu li").removeClass("ui-screen-hidden");
$("input", form).val("");
});
});
For reference:
https://forum.jquery.com/topic/cannot-read-property-jqmdata-of-undefined
This seemed to fix it for me -
In the 'pagecontainerhide' handler, change the argument in the
pageIsSelectmenuDialog function from 'data.toPage' to 'data.prevPage' as in:
if ( !pageIsSelectmenuDialog( data.prevPage ) ) {
       return;
}

Select2 with a checkbox list for a multiple select

I need to implement a select similar to this http://www.erichynds.com/examples/jquery-ui-multiselect-widget/demos/
I want to use select2 for this, but I haven't been able to find anything from the creator of the select2 that would support this style of dropdown with checkboxes in it. Does anyone know a way to do this?
I've faced a similar need but was not able to find it.
The solution I've came across was using the flag closeOnSelect set to false
$("#yadayada").select2({closeOnSelect:false});
http://jsfiddle.net/jEADR/521/
Seems this is old post, but as it is very common issue, I`m posting this here.
I found that the author already added a plugin to select2 for this feature to have checkbox-like selection and the dropdown does not hide on click:
https://github.com/wasikuss/select2-multi-checkboxes
Example:
$('.select2-multiple').select2MultiCheckboxes({
placeholder: "Choose multiple elements",
})
http://jsfiddle.net/wasikuss/gx93rwnk/
All other features of select2 are preserved. There are few more predefined options set to work properly.
I managed to put something together, not perfect, but it works.
https://jsfiddle.net/Lkkm2L48/7/
jQuery(function($) {
$.fn.select2.amd.require([
'select2/selection/single',
'select2/selection/placeholder',
'select2/selection/allowClear',
'select2/dropdown',
'select2/dropdown/search',
'select2/dropdown/attachBody',
'select2/utils'
], function (SingleSelection, Placeholder, AllowClear, Dropdown, DropdownSearch, AttachBody, Utils) {
var SelectionAdapter = Utils.Decorate(
SingleSelection,
Placeholder
);
SelectionAdapter = Utils.Decorate(
SelectionAdapter,
AllowClear
);
var DropdownAdapter = Utils.Decorate(
Utils.Decorate(
Dropdown,
DropdownSearch
),
AttachBody
);
var base_element = $('.select2-multiple2')
$(base_element).select2({
placeholder: 'Select multiple items',
selectionAdapter: SelectionAdapter,
dropdownAdapter: DropdownAdapter,
allowClear: true,
templateResult: function (data) {
if (!data.id) { return data.text; }
var $res = $('<div></div>');
$res.text(data.text);
$res.addClass('wrap');
return $res;
},
templateSelection: function (data) {
if (!data.id) { return data.text; }
var selected = ($(base_element).val() || []).length;
var total = $('option', $(base_element)).length;
return "Selected " + selected + " of " + total;
}
})
});
});
CSS:
.select2-results__option .wrap:before{
font-family:fontAwesome;
color:#999;
content:"\f096";
width:25px;
height:25px;
padding-right: 10px;
}
.select2-results__option[aria-selected=true] .wrap:before{
content:"\f14a";
}
Add just two emoji with css
.select2-results__options {
&[aria-multiselectable=true] {
.select2-results__option {
&[aria-selected=true]:before {
content: '☑';
padding: 0 0 0 4px;
}
&:before {
content: '◻';
padding: 0 0 0 4px;
}
}
}
}
You see this sample a RTL select2 with emoji based checkbox
Here is very simple snippet, without strange modyfing of js - pure and simple css (with "Font Awesome")
$('.select2[multiple]').select2({
width: '100%',
closeOnSelect: false
})
#body{
padding: 30px
}
.select2-results__options[aria-multiselectable="true"] li {
padding-left: 30px;
position: relative
}
.select2-results__options[aria-multiselectable="true"] li:before {
position: absolute;
left: 8px;
opacity: .6;
top: 6px;
font-family: "FontAwesome";
content: "\f0c8";
}
.select2-results__options[aria-multiselectable="true"] li[aria-selected="true"]:before {
content: "\f14a";
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/css/select2.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/js/select2.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/js/all.min.js"></script>
<div id="body">
<select name="fabric_color_en[]" id="fabric_color_en[]" multiple="multiple" class="form-control select2">
<option value="Beige">
Beige
</option>
<option value="Red">
Red
</option>
<option value="Petrol">
Petrol
</option>
<option value="Royal Blue">
Royal Blue
</option>
<option value="Dark Blue">
Dark Blue
</option>
<option value="Bottle Green">
Bottle Green
</option>
<option value="Light Grey">
Light Grey
</option>
</select>
</div>
Now the code is ready to use for you to implement the multiple checkboxes select2 dropdown.
Enjoy :)
//===============================================
//Start - Select 2 Multi-Select Code======================================================
var Select2MultiCheckBoxObj = [];
var id_selectElement = 'id_SelectElement';
var staticWordInID = 'state_';
function AddItemInSelect2MultiCheckBoxObj(id, IsChecked) {
if (Select2MultiCheckBoxObj.length > 0) {
let index = Select2MultiCheckBoxObj.findIndex(x => x.id == id);
if (index > -1) {
Select2MultiCheckBoxObj[index]["IsChecked"] = IsChecked;
}
else {
Select2MultiCheckBoxObj.push({ "id": id, "IsChecked": IsChecked });
}
}
else {
Select2MultiCheckBoxObj.push({ "id": id, "IsChecked": IsChecked });
}
}
function IsCheckedAllOption(trueOrFalse) {
$.map($('#' + id_selectElement + ' option'), function (option) {
AddItemInSelect2MultiCheckBoxObj(option.value, trueOrFalse);
});
$('#' + id_selectElement + " > option").not(':first').prop("selected", trueOrFalse); //This will select all options and adds in Select2
$("#" + id_selectElement).trigger("change");//This will effect the changes
$(".select2-results__option").not(':first').attr("aria-selected", trueOrFalse); //This will make grey color of selected options
$("input[id^='" + staticWordInID + "']").prop("checked", trueOrFalse);
}
$(document).ready(function () {
//Begin - Select 2 Multi-Select Code
$.map($('#' + id_selectElement + ' option'), function (option) {
AddItemInSelect2MultiCheckBoxObj(option.value, false);
});
function formatResult(state) {
if (Select2MultiCheckBoxObj.length > 0) {
var stateId = staticWordInID + state.id;
let index = Select2MultiCheckBoxObj.findIndex(x => x.id == state.id);
if (index > -1) {
var checkbox = $('<div class="checkbox"><input class="select2Checkbox" id="' + stateId + '" type="checkbox" ' + (Select2MultiCheckBoxObj[index]["IsChecked"] ? 'checked' : '') +
'><label for="checkbox' + stateId + '">' + state.text + '</label></div>', { id: stateId });
return checkbox;
}
}
}
let optionSelect2 = {
templateResult: formatResult,
closeOnSelect: false,
width: '100%'
};
let $select2 = $("#" + id_selectElement).select2(optionSelect2);
//var scrollTop;
//$select2.on("select2:selecting", function (event) {
// var $pr = $('#' + event.params.args.data._resultId).parent();
// scrollTop = $pr.prop('scrollTop');
// let xxxx = 2;
//});
$select2.on("select2:select", function (event) {
$("#" + staticWordInID + event.params.data.id).prop("checked", true);
AddItemInSelect2MultiCheckBoxObj(event.params.data.id, true);
//If all options are slected then selectAll option would be also selected.
if (Select2MultiCheckBoxObj.filter(x => x.IsChecked === false).length === 1) {
AddItemInSelect2MultiCheckBoxObj(0, true);
$("#" + staticWordInID + "0").prop("checked", true);
}
});
$select2.on("select2:unselect", function (event) {
$("#" + staticWordInID + "0").prop("checked", false);
AddItemInSelect2MultiCheckBoxObj(0, false);
$("#" + staticWordInID + event.params.data.id).prop("checked", false);
AddItemInSelect2MultiCheckBoxObj(event.params.data.id, false);
});
$(document).on("click", "#" + staticWordInID + "0", function () {
//var b = !($("#state_SelectAll").is(':checked'));
var b = $("#" + staticWordInID + "0").is(':checked');
IsCheckedAllOption(b);
//state_CheckAll = b;
//$(window).scroll();
});
$(document).on("click", ".select2Checkbox", function (event) {
let selector = "#" + this.id;
let isChecked = Select2MultiCheckBoxObj[Select2MultiCheckBoxObj.findIndex(x => x.id == this.id.replaceAll(staticWordInID, ''))]['IsChecked'];
$(selector).prop("checked", isChecked);
});
});
//====End - Select 2 Multi-Select Code==
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/js/bootstrap.bundle.min.js" integrity="undefined" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<div class="container-fluid">
<hr/>
<p>Here, you can select any item by clicking on row or checked in on checkbox and can unselect in reverse way.</p>
<p>But I didn't give the option to select "SelectAll" option by clicking on his row, you can select-all and unselect-all by click on checkbox only rather than row.</p>
<div class="row" style="width:50%">
<label for="id_SelectElement" class="col-sm-2">Part Name: </label>
<div class="col-sm-4">
<select id="id_SelectElement" placeholder="Select Text" multiple>
<option value="0" disabled>Select All</option>
<option value="11">Php</option>
<option value="22">Bootstrap</option>
<option value="33">sql</option>
<option value="44">Node Js</option>
<option value="55">Laravel</option>
<option value="66">Jquery</option>
<option value="77">React</option>
<option value="88">Vew.JS</option>
<option value="99">MVC</option>
<option value="10">DotNetCore</option>
<option value="12">Java</option>
<option value="13">Artifical Intiligence</option>
<option value="14">Data Structure</option>
<option value="15">Data Science</option>
<option value="16">Robotics</option>
<option value="17">Node Js 2</option>
<option value="18">Laravel 23</option>
<option value="19">Jquery 3.4</option>
</select>
</div>
</div>
</div>
Another workaround is to "prepend" checkbox icons using CSS. I use bootstrap theme - your select2-container may be different.
.select2-container--bootstrap .select2-results__option[aria-selected=true]:before { content:'\e067 '; padding:0 8px 0 0px; font-family:'Glyphicons Halflings' }
.select2-container--bootstrap .select2-results__option:before { content:'\e157 '; padding:0 8px 0 0px; font-family:'Glyphicons Halflings' }

copy data from one Html.listboxfor to other listbox in asp.net mvc

I have two Html.ListBoxFor called A & B.
1) A has data populated from DB & B is empty.
2) I want a functionality like this where items from list A are placed into list B.
$('.add').on('click', function() {
var options = $('select.multiselect1 option:selected').sort().clone();
$('select.multiselect2').append(options);
});
$('.addAll').on('click', function() {
var options = $('select.multiselect1 option').sort().clone();
$('select.multiselect2').append(options);
});
$('.remove').on('click', function() {
$('select.multiselect2 option:selected').remove();
});
$('.removeAll').on('click', function() {
$('select.multiselect2').empty();
});
3) I tried this with asp.net mvc, but I was unable to fetch the selected items in model & controller.
4) I want a way by which we can perform this in asp.net mvc. If there can be some way in mvc then I would be able to store that data in SQL DB
5) Its jquery sibling is here
Any help would be appreciated
I think this will help you.
Blockquote
Html file
Fruits:
<select multiple="multiple" id="a">
<option value="1">Apple</option>
<option value="2">Orange</option>
<option value="3">Banana</option>
</select>
<input type="button" id="add" value="Add"/>
<input type="button" id="addall" value="Add all"/>
<select multiple="multiple" id="b">
</select>
Javascript File
$("#add").bind("click", function () {
addOption(false);
});
$("#addall").bind("click", function () {
addOption(true);
});
function addOption(isAll){
var option = $("#a option");
if (!isAll) {
option = $("#a option:selected");
} else {
$("#b").html("");
}
$(option).each(function () {
var val = $(this).val();
var text = $(this).text();
$("#b").append($(this)[0].outerHTML);
$(this).remove();
});
}

Icons in Custom jQuery Mobile Select Menu

I'm using a custom select menu from jQuery Mobile, and I'd like to put icons into the custom pop-up menu to accompany each option. I'm applying the data-icon attribute to each option, like so:
<select name='mySelect' id='mySelect' data-icon='gear'>
<option value='0' data-icon='star'>Option 0</option>
<option value='1' data-icon='star'>Option 1</option>
<option value='2' data-icon='star' selected="selected">Option 2</option>
</select>
FWIW, I've already verified that my custom icons work in the select button itself. Am I just completely wrong in expecting icons to appear in the custom menu?
This is not supported by default but here is a quick piece of code to make it possible:
//wait for the correct page to initialize
$(document).delegate('#home', 'pageinit', function () {
//loop through each of the SELECT elements in this page
$.each($(this).find('select'), function () {
//get the ID of this select because it's menu's ID is based off of it
var currentID = this.id;
//iterate through each of the OPTION elements for this SELECT element
$.each($(this).find('option'), function (index, element) {
//if the OPTION element has the `data-icon` attribute
if ($(element).attr('data-icon') != undefined) {
//update the menu for this SELECT by adding an icon SPAN element
//to each of the OPTION elements that has a `data-icon` attribute
$('#' + currentID + '-menu').children().eq(index).find('.ui-btn-inner').append('<span class="ui-icon ui-icon-' + $(element).attr('data-icon') + ' ui-icon-shadow" />');
}
});
});
});​​
Here is a demo: http://jsfiddle.net/NHQGD/

Resources