The select2 item cannot selected - jquery-select2

Why my select2's items cannot be selected.
You can copy my code and save as html, run it by yourself.
And you can see the demo online at http://devhelp.duapp.com/select2/
my html and js code
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<link href="http://cdn.bootcss.com/select2/3.4.5/select2.min.css" rel="stylesheet">
<script src="http://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script>
<script src="http://cdn.bootcss.com/select2/3.4.5/select2.min.js"></script>
<input type="hidden" name="originPlace" value="" />
demo online
<script >
$(document).ready(function() {
$('input[name=originPlace]').select2({
placeholder: "please select country or city",
minimumInputLength: 2,
width: 300,
ajax: {
url: 'http://devhelp.duapp.com/select2/data.php',
dataType: 'jsonp',
data: function(term, page) {
return {query: term,locale:'en-GB'};
},
results: function(data, page) {
if (data.status == 1) {
return {results: data.data.Places};
} else {
return{results: {}};
}
}
},
formatResult: formatSelectSelect,
formatSelection: formatSelectSelect
});
function formatSelectSelect(data){
var liStr = "";
if (data.CityId === "-sky") {
liStr = data.PlaceName + "(ALL)-" + data.PlaceId.replace('-sky', '');
} else {
liStr = data.PlaceName + "[" + data.CountryName + "]-" + data.PlaceId.replace('-sky', '');
}
return liStr;
}
});
</script>

Here is a jsfiddle of it working: http://jsfiddle.net/tk5446/kvLd6/
Just needed to add the "id" entry like so:
id: function(bond){return {id: bond._id};},

Related

Redirect before selecting an item Select2

I'm using Select2 v4.0.3 and I populate the element using ajax.
$("#el").select2({
multiple: true
maximumSelectionSize: 1,
ajax: {
url: url,
data: function (params) {
return {
name: params.term
};
},
processResults: function (data) {
return {
results: $.map(data.results, function(obj) {
return {id: obj.id, text: obj.name, key: obj.key};
}
})
};
}
}
});
I want to redirect the client before a result is selected. The problem is I need the key attribute from the clicked result. To understand better what I want to do, I paste here a snippet that works after the selection is made.
$("#el").on("select2:select", function(e) {
var selected = $(this).select2('data')[0];
location.href = base_url + '?key=' + selected.key;
});
You can use event.params.args.data.id to get the key attribute from the clicked result. So, your code would probably work like:
$("#el").on("select2:select", function(e) {
var selected = event.params.args.data.id;
location.href = base_url + '?key=' + selected;
});
I slightly modified the official Github repositories example to show my point.
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
</head>
<body>
<select class="js-data-example-ajax" style="width: 100%">
<option value="3620194" selected="selected">select2/select2</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<script>
$(".js-data-example-ajax").select2({
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
delay: 250,
data: function(params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function(data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: $.map(data.items, function(ghrepo) {
return {
text: ghrepo.archive_url,
id: ghrepo.archive_url
}
})
}
},
cache: true
},
escapeMarkup: function(markup) {
return markup;
},
minimumInputLength: 1
}).on('select2:selecting', function(event, params) {
event.preventDefault();
repoId = event.params.args.data.id;
console.log(repoId);
});
</script>
</body>
</html>

How to make jquery autocomplete to work in latest free jqgrid

I tried to use edittype: custom in latest free jqgrid in Github.
Autocomplete window width is same as column width and is too small in mobile.:
How to make autocomplete dropdown wider, more native in mobile?
Complete testcase:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/redmond/jquery-ui.css" />
<link rel="stylesheet" href="http://rawgit.com/free-jqgrid/jqGrid/master/css/ui.jqgrid.css" type="text/css" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.js"></script>
<script>
$(document).bind('mobileinit', function () {
$.mobile.changePage.defaults.changeHash = false;
$.mobile.hashListeningEnabled = false;
$.mobile.pushStateEnabled = false;
});
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js"></script>
<script src="http://rawgit.com/commadelimited/autoComplete.js/master/jqm.autoComplete-1.5.2.js"></script>
<script src="http://rawgit.com/free-jqgrid/jqGrid/master/js/jquery.jqgrid.src.js"></script>
<script>
$(document).ready(function () {
var mydata = [
{ id: 0, Name: "Indiana", Category: "IN" },
{ id: 1, Name: "California", Category: "CA" },
{ id: 2, Name: "Pennsylvania", Category: "PA" },
{ id: 3, Name: "Texas", Category: "TX" }
];
var lastSel;
var grid = $("#list");
grid.jqGrid({
data: mydata,
datatype: 'local',
colModel: [
{
name: 'Name', editable: true, width: 100,
edittype: 'custom',
editoptions: {
custom_element: function (value, options) {
var elemStr = '<div>', newel, width;
if (options.id === options.name) {
// form edit
elemStr += '<input class="FormElement" size="' +
options.size + '"' + ' id="' + options.id + '"';
}
else { // inline edit
width = getColumnByName(grid, options.name).width - 2;
elemStr += '<input class="FormElement" ' +
' style="width:' + width + 'px" ' + ' id="' + options.id + '_x"';
}
elemStr += ' value="' + value + '"/>';
elemStr += '<ul id="Xsuggestions" data-role="listview" data-inset="true"></ul></div>';
newel = $(elemStr)[0];
setTimeout(function () {
$('#Xsuggestions').listview().listview('refresh');
input_autocomplete(newel, options.id + '_x');
}, 100);
return newel;
},
custom_value: function (elem) {
return elem.find("input").val();
}
}
},
{ name: 'Category', index: 'Category', width: 50, editable: true }
],
sortname: 'Name',
ignoreCase: true,
gridview: true,
viewrecords: true,
rownumbers: true,
height: "100%",
sortorder: "desc",
pager: '#pager',
editurl: 'clientArray',
ondblClickRow: function (id, ri, ci) {
grid.jqGrid('editRow', id, true, null, null, 'clientArray', {});
},
onSelectRow: function (id) {
if (id && id !== lastSel) {
if (typeof lastSel !== "undefined") {
grid.jqGrid('restoreRow', lastSel);
}
lastSel = id;
}
}
});
});
var getColumnByName = function (grid, columnName) {
var cm = grid.jqGrid('getGridParam', 'colModel'), i = 0, l = cm.length;
for (; i < l; ++i) {
if (cm[i].name === columnName) {
return cm[i];
}
}
return null;
};
function input_autocomplete(newel, id) {
var input = $("input", newel);
//if (input.length === 0) {
// return;
//}
input[0].ischanged = false;
input.autocomplete({
target: $('#Xsuggestions'),
source: autocompleteData,
callback: function (e) {
var $a = $(e.currentTarget);
$('#' + id).val($a.data('autocomplete').label);
$('#' + id).autocomplete('clear');
input[0].ischanged = true;
},
link: '#',
//link: 'target.html?term=',
minLength: 1
});
}
</script>
</head>
<body>
<div data-role="page" id="mainPage">
<table>
<tr>
<td>
<input type="text" id="searchField">
<ul id="suggestions" data-role="listview" data-inset="true"></ul>
</td>
</tr>
</table>
<table id="list"><tbody><tr><td /></tr></tbody></table>
<div id="pager"></div>
</div>
<script>
var autocompleteData = $.parseJSON('[{"value":"AL","label":"Alabama"},{"value":"AK","label":"Alaska"},{"value":"CA","label":"California"},{"value":"CO","label":"Colorado"},{"value":"CT","label":"Connecticut"},{"value":"NC","label":"North Carolina"},{"value":"ND","label":"North Dakota"},{"value":"NI","label":"Northern Marianas Islands"},{"value":"OH","label":"Ohio"},{"value":"OK","label":"Oklahoma"},{"value":"OR","label":"Oregon"},{"value":"PA","label":"Pennsylvania"},{"value":"PR","label":"Puerto Rico"},{"value":"RI","label":"Rhode Island"},{"value":"WV","label":"West Virginia"},{"value":"WI","label":"Wisconsin"},{"value":"WY","label":"Wyoming"}]');
$("#mainPage").bind("pageshow", function (e) {
$("#searchField").autocomplete({
target: $('#suggestions'),
source: autocompleteData,
callback: function (e) {
var $a = $(e.currentTarget);
$('#searchField').val($a.data('autocomplete').label);
$("#searchField").autocomplete('clear');
},
link: 'target.html?term=',
minLength: 1
});
});
</script>
</body>
</html>

How can we implement select All option in Kendo MultiselectFor

How can we implement select all option in Kendo Multiselect For?
#(Html.Kendo().MultiSelectFor(model => model.TestData)
.DataTextField("DataText")
.DataValueField("DataValue")
.Placeholder("Select..")
.Events(e => e.DataBound("CheckIfEmpty"))
.AutoBind(false)
.Enable(false)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Action", "Controller").Data("filterData");
})
.ServerFiltering(false);
})
)
Please check below code snippet.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Kendo UI Snippet</title>
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1119/styles/kendo.common.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1119/styles/kendo.rtl.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1119/styles/kendo.default.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1119/styles/kendo.dataviz.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1119/styles/kendo.dataviz.default.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1119/styles/kendo.mobile.all.min.css">
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://cdn.kendostatic.com/2014.3.1119/js/kendo.all.min.js"></script>
</head>
<body>
<div class="demo-section k-header">
<select id="TestData" data-placeholder="Select movie..."></select>
</div>
<div>
<button type="button" onclick="SelectAllClick();">Select All</button>
</div>
<script>
$(document).ready(function () {
var data = [
{ text: "12 Angry Men", value: "1" },
{ text: "Il buono, il brutto, il cattivo.", value: "2" },
{ text: "Inception", value: "3" },
{ text: "One Flew Over the Cuckoo's Nest", value: "4" },
{ text: "Pulp Fiction", value: "5" },
{ text: "Schindler's List", value: "6" },
{ text: "The Dark Knight", value: "7" },
{ text: "The Godfather", value: "8" },
{ text: "The Godfather: Part II", value: "9" },
{ text: "The Shawshank Redemption", value: "10" },
{ text: "The Shawshank Redemption 2", value: "11" }
];
$("#TestData").kendoMultiSelect({
dataTextField: "text",
dataValueField: "value",
dataSource: data
});
});
function SelectAllClick() {
var multiSelect = $("#TestData").data("kendoMultiSelect");
var selectedValues = "";
var strComma = "";
for (var i = 0; i < multiSelect.dataSource.data().length; i++) {
var item = multiSelect.dataSource.data()[i];
selectedValues += strComma + item.value;
strComma = ",";
}
multiSelect.value(selectedValues.split(","));
}
</script>
</body>
</html>
Let me know if any concern.
Something like this should work:
<script>
$('#selectAll').click(function(){
var ctl = $('#TestData').data('kendoMultiSelect');
var opts = ctl.dataSource.data();
var selected = [];
for (var idx = 0; idx < opts.length; idx++) {
selected.push(opts[idx].value);
}
ctl.value(selected);
});
</script>
If you're using something like underscore, I can make it even easier for you by doing something like this:
<script>
$('#selectAll').click(function(){
var ctl = $('#TestData').data('kendoMultiSelect');
var opts = ctl.dataSource.data();
var selected = _.pluck(opts, 'value');
ctl.value(selected);
});
</script>

Dymanic listview construction visible in jQuery Mobile 1.4.2 transition

I have a Single Page transition from #homepage to #addresses where the page #addresses include a dynamic listview build based in an $.ajax WebApi call.
The problem is that it's visible the construction of the listview when we arrive at the second page, and I want to avoid that, I want the list all build when we land in the #addresses page.
I also have a delay click in the listview in iPhone.
My code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>izigo.mobile</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css">
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$(document).bind("mobileinit", function ()
{
$.mobile.toolbar.prototype.options.addBackBtn = true;
$.mobile.toolbar.prototype.options.backBtnText = "voltar";
$.mobile.page.prototype.options.domCache = true;
});
</script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
<script>
/* Pass data with changePage */
$(document).on("pageinit", "#homepage", function ()
{
$(".category").on("click", function ()
{
$.mobile.pageContainer.pagecontainer("change", "#addresses",
{
categoryId: this.id,
transition: "slide"
});
});
});
/* retrieve data and run function to add elements */
$(document).on("pagebeforechange", function (e, data)
{
if (data.toPage[0].id == "addresses")
{
var categoryId = data.options.categoryId;
clearListCategory("#addresses");
buildListCategory("#addresses", categoryId);
}
});
function clearListCategory(page)
{
var $page = $(page);
$("ul", $page).remove();
}
function buildListCategory(page, categoryId)
{
$.ajax({
type: "POST",
url: "http://10.0.0.200/api/Mobile/GetAddresses",
crossDomain: false,
beforeSend: function () { $.mobile.loading('show') },
complete: function () { $.mobile.loading('hide') },
data: { CategoryId: categoryId },
dataType: 'json',
success: function (addresses)
{
showAddresses(page, addresses);
},
error: function () {
console.log("loadList error!");
}
});
}
function showAddresses(page, addresses)
{
var $page = $(page);
var list = $("<ul/>", {
"data-role": "listview"
});
var items = '';
$.each(addresses, function (i, address)
{
items = $("<li>" + address.Name + "</li>");
list.append(items);
});
$(".ui-content", $page).append(list);
$("ul", $page).listview();
}
</script>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<!-- home-page -->
<div data-role="page" id="homepage">
<div data-role="header" data-position="fixed"><h1>mobile</h1></div>
<div class="ui-content" role="main">
<ul data-role="listview" id="categories">
<li>Oficina</li>
<li>Seguro</li>
<li>Reboque</li>
</ul>
</div>
</div>
<!-- page addresses list -->
<div data-role="page" id="addresses">
<div data-role="header" data-position="fixed"><h1>mobile</h1></div>
<div class="ui-content" role="main"></div>
</div>
</body>
</html>
The code you're using, you populate listview on pagebeforechange event, which is triggered before any other page event. You should populate listview before you navigate to target page, using .success or .complete callback.
$.ajax({
type: "POST",
url: "URL",
crossDomain: false,
beforeSend: function () {
$.mobile.loading('show')
},
complete: function () {
$.mobile.loading('hide')
},
data: {
CategoryId: categoryId
},
dataType: 'json',
success: function (addresses) {
showAddresses(page, addresses);
$.mobile.pageContainer.pagecontainer("change", "#addresses");
},
error: function () {
console.log("loadList error!");
}
});
Demo - Code

Fusion Table Layer Wizard shows search but not map

I found several other people on here had the same issue with the Fusion Table Wizard generating HTML that works in the preview but when you try to embed the code on your own webpage pieces are missing. Mine for example, will show the search bar but not the map. Someone else had the same problem and it turned out that quotes were missing around the id number. But mine does have the appropriate quotes. So I'm wondering what is wrong with my code. I've compared my code to theirs several times looking for what is missing but can't figure it out.
Our webpage is hosted by jimdo, and I have to use the html/widget. I copy and paste the code into that. But it does say that some code requires you to edit the head section. That wouldn't be the problem would it? And if it is, what would I put in the head section and what would I put in the body section?
Here is my code:
<!DOCTYPE html>
<html>
<head>
<style>
#map-canvas { width:500px; height:400px; }
.layer-wizard-search-label { font-family: sans-serif };
</style>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
var map;
var layer_0;
var layer_1;
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(45.0817001045586, -89.74025),
zoom: 6
});
var style = [
{
featureType: 'all',
elementType: 'all',
stylers: [
{ saturation: 11 }
]
}
];
var styledMapType = new google.maps.StyledMapType(style, {
map: map,
name: 'Styled Map'
});
map.mapTypes.set('map-style', styledMapType);
map.setMapTypeId('map-style');
layer_0 = new google.maps.FusionTablesLayer({
query: {
select: "col18",
from: "1_rIjSmE6MLjWMF4JH-OIzHFcYCjKr-8eytn9v6Y"
},
map: map,
styleId: 2,
templateId: 3
});
layer_1 = new google.maps.FusionTablesLayer({
query: {
select: "col4",
from: "1ZLOwVcCWsIA-1WNg_yICWjaRdWOTeVy9xpudaQ"
},
map: map
});
}
function changeMap_0() {
var whereClause;
var searchString = document.getElementById('search-string_0').value.replace(/'/g, "\\'");
if (searchString != '--Select--') {
whereClause = "'Counties' CONTAINS IGNORING CASE '" + searchString + "'";
}
layer_0.setOptions({
query: {
select: "col18",
from: "1_rIjSmE6MLjWMF4JH-OIzHFcYCjKr-8eytn9v6Y",
where: whereClause
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<div style="margin-top: 10px;">
<label class="layer-wizard-search-label">
Counties
<input type="text" id="search-string_0">
<input type="button" onclick="changeMap_0()" value="Search">
</label>
</div>
</body>
</html>
Can somebody help me, because I have been doing this for days now. And have finally decided to actually ask for help. Any input you have would be greatly appreciated!
Thanks, Angie
Paste this:
<div id="map-canvas" style="width:500px; height:400px;"></div>
<div style="margin-top: 10px;">
<label class="layer-wizard-search-label">
Counties
<input type="text" id="search-string_0">
<input type="button" onclick="changeMap_0()" value="Search">
</label>
</div>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
var map;
var layer_0;
var layer_1;
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(45.0817001045586, -89.74025),
zoom: 6
});
var style = [
{
featureType: 'all',
elementType: 'all',
stylers: [
{ saturation: 11 }
]
}
];
var styledMapType = new google.maps.StyledMapType(style, {
map: map,
name: 'Styled Map'
});
map.mapTypes.set('map-style', styledMapType);
map.setMapTypeId('map-style');
layer_0 = new google.maps.FusionTablesLayer({
query: {
select: "col18",
from: "1_rIjSmE6MLjWMF4JH-OIzHFcYCjKr-8eytn9v6Y"
},
map: map,
styleId: 2,
templateId: 3
});
layer_1 = new google.maps.FusionTablesLayer({
query: {
select: "col4",
from: "1ZLOwVcCWsIA-1WNg_yICWjaRdWOTeVy9xpudaQ"
},
map: map
});
}
function changeMap_0() {
var whereClause;
var searchString = document.getElementById('search-string_0').value.replace(/'/g, "\\'");
if (searchString != '--Select--') {
whereClause = "'Counties' CONTAINS IGNORING CASE '" + searchString + "'";
}
layer_0.setOptions({
query: {
select: "col18",
from: "1_rIjSmE6MLjWMF4JH-OIzHFcYCjKr-8eytn9v6Y",
where: whereClause
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
As it seems everything except the contents of <body> will be removed when you paste a complete HTML-source.

Resources