Add an attribute to the generated tag select2 - jquery-select2

Can you please tell me how can I add the type attribute to the generated tag?
$(".select_multiple").select2({
tags: true,
createTag: function (params) {
if (!Number.isInteger(parseInt(params.term))) {
return null;
}
return {
id: params.term,
text: params.term,
newOption: true,
type: "text_type"
}
}
})
$('.select_multiple').on('select2:select', function (e) {
console.log($(e.params.data.element).data('type'));
});
.select_multiple {
width: 500px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js"></script>
<select class="select_multiple" multiple="multiple">
<option data-type="1">Date</option>
</select>

Related

Is it possible to use template for display text of Kendo UI dropdownlist which uses MVVM

I have a Kendo UI dropdownlist, which using Kendo MVVM features:
<select id="SearchPicker"
data-bind="source: LocationTypeDropDown, value: LocationType"
data-role="dropdownlist"
data-value-field="Code"
data-text-field="Name"
data-option-label="All"
data-value-primitive="true"
data-cascade-from="ddlSite"
data-auto-bind="false">
</select>
But for display text of the items, indeed I want a format like Code - Name, and I wonder how can I change the display template?
In MVC I know there is a .ClientTemplate() method which enable me to write .ClientTemplate("#=Code# - #=Name#"), but as I am using MVVM features, how can I acheive something like this?
EDIT
Other than the drop down list item options, is it possible that the selected value (like "Oranges" below)
be shown using template as well? ("2 - Oranges")
Try with this solution JSFiddle
var viewModel = kendo.observable({
selectedProduct: null,
onChange: function () {
var selectedFruit = this.get("selectedFruit");
alert("Id: " + selectedFruit.id + " - Name: " + selectedFruit.name);
},
fruits: new kendo.data.DataSource({
data: [
{ id: 1, name: "Apples" },
{ id: 2, name: "Oranges" },
{ id: 3, name: "Bananas" }],
schema: {
model: {
fields: {
id: { type: "number" },
name: { type: "string" }
}
}
}
})
});
kendo.bind("#example", viewModel);
<link rel="stylesheet" type="text/css" href="https://kendo.cdn.telerik.com/2016.1.112/styles/kendo.common.min.css">
<link rel="stylesheet" type="text/css" href="https://kendo.cdn.telerik.com/2016.1.112/styles/kendo.rtl.min.css">
<link rel="stylesheet" type="text/css" href="https://kendo.cdn.telerik.com/2016.1.112/styles/kendo.silver.min.css">
<link rel="stylesheet" type="text/css" href="https://kendo.cdn.telerik.com/2016.1.112/styles/kendo.mobile.all.min.css">
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2016.1.112/js/kendo.all.min.js"></script>
<div id="example">
<p>Kendo UI DropDownList</p>
<select data-role="dropdownlist"
data-option-label="Select Item..."
data-bind="value: selectedFruit,source: fruits, events: {
change: onChange
}" data-template="select-template" data-value-template="select-template" data-text-field="name" data-value-field="id">
</select>
<script id="select-template" type="text/x-kendo-template">
<option value="#: id #">#: id # - #: name #</option>
</script>
</div>

The select2 item cannot selected

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};},

JQuery Autocomplete

I've got a problem with my jQuery autocomplete field. Its some kind of strange.
This is my autocomplete field and script. The response from my mvc function works fine. The Dropdownlist is visible entries. But when I'm trying to select an item the resultlist simply disappears. Does anyone have an idea?
<div class="ui-widget">
<input id="newPlayerName" type="text" name="newPlayerName" onkeyup="checkRegistration()" />
</div>
code:
<script type="text/javascript">
$(function () {
$('#newPlayerName').autocomplete({
source: function (request, response) {
$.ajax({
url: '/Trainer/Search',
data: {
searchTerm: request.term
},
dataType: 'json',
type: 'POST',
minLength: 1,
success: function (data) {
response(data);
}
});
},
select: function (event, ui) {
checkRegistration(ui.item.value);
},
focus: function (event, ui) {
event.preventDefault();
$("#newPlayerName").val(ui.item.label);
}
});
});
</script>
Ah ... this are the jquery scripts I'm using...
<script src="/Scripts/jquery-1.9.0.js" type="text/javascript"></script>
<script src="/Scripts/jquery-ui-1.10.0.custom.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery-ui-1.10.0.custom.js" type="text/javascript"></script>
One thing that seems wrong with the code you have shown is the fact that you have included the jquery-ui script twice (the minified and standard versions). You should have only one:
<script src="/Scripts/jquery-1.9.0.js" type="text/javascript"></script>
<script src="/Scripts/jquery-ui-1.10.0.custom.min.js" type="text/javascript"></script>
$(function () {
var getData = function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetMultiProductList",
data: "{'term':'" + $("#txtAutoCompleteMulti").val() + "'}",
dataType: "json",
success: function (data) {
response($.map(data.d, function (item) {
if (item != null)
return { label: item.label, title: item.value }//value: item.label,
}))
},
error: function (result) {
alert("Error");
}
});
};
var selectItem = function (event, ui) { $("#txtAutoCompleteMulti").val(ui.item.value); return false; }
$("#txtAutoCompleteMulti").autocomplete({
source: getData,
select: selectItem,
_resizeMenu: function () {
this.menu.element.outerWidth(500);
},
search: function (event, ui) { },
minLength: 1,
change: function (event, ui) {
if (!ui.item) {
$('#txtAutoCompleteMulti').val("")
}
},
select: function (event, ui) {
$("#txtAutoCompleteMulti").prop('title', ui.item.title)
},
autoFocus: true,
delay: 500
});
});
.ui-autocomplete {
max-height: 300px;
overflow-y: auto;
overflow-x: hidden;
}
.ui-autocomplete-loading {
background: url('img/Progress_indicator.gif') no-repeat right center;
}
.seachbox {
border: 1px solid #ccc;
border-radius: 4px;
width: 250px;
padding: 6px 25px 6px 6px;
transition: border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s;
}
<link href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
<div>
<table style="width: 100%;">
<tr>
<td style="width: 20%">Product Name :</td>
<td>
<input type="text" id="txtAutoCompleteMulti" placeholder="Seach Product" class="seachbox" />
</td>
</tr>
</table>
</div>
c# code using webmethod

jQuery UI combobox does not render correctly in IE 9.x?

I have a html page based on Combobox autocomplete demo at Combobox jQuery Autocomplete Demo. The problem is that the combobox renders perfectly in FireFox 13.x. However, in IE 9.x (64-bit), it does the autocomplete part correctly, but is strange in appearance as you can see at this link: Strange jQuery Combobox Appearance in IE 9.x. I thought jQuery was the perfect cross-browser technology, but it doesn't look like it. Or may be I am missing something in my html code? The complete html code is as given below.
<html>
<head>
<meta charset="utf-8">
<title>jQuery UI Example Page</title>
<link type="text/css" href="css/cupertino/jquery-ui-1.8.21.custom.css" rel="stylesheet" />
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.21.custom.min.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<style>
.ui-combobox {
position: relative;
display: inline-block;
}
.ui-combobox-toggle {
position: absolute;
top: 0;
bottom: 0;
margin-left: -1px;
padding: 0;
/* adjust styles for IE 6/7 */
*height: 1.7em;
*top: 0.1em;
}
.ui-combobox-input {
margin: 0;
padding: 0.3em;
}
</style>
<script type="text/javascript">
(function ($) {
$.widget("ui.combobox", {
_create: function () {
var input,
self = this,
select = this.element.hide(),
selected = select.children(":selected"),
value = selected.val() ? selected.text() : "",
wrapper = this.wrapper = $("<span>")
.addClass("ui-combobox")
.insertAfter(select);
input = $("<input>")
.appendTo(wrapper)
.val(value)
.addClass("ui-state-default ui-combobox-input")
.autocomplete({
delay: 0,
minLength: 0,
source: function (request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response(select.children("option").map(function () {
var text = $(this).text();
if (this.value && (!request.term || matcher.test(text)))
return {
label: text.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>"),
value: text,
option: this
};
}));
},
select: function (event, ui) {
ui.item.option.selected = true;
self._trigger("selected", event, {
item: ui.item.option
});
},
change: function (event, ui) {
if (!ui.item) {
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i"),
valid = false;
select.children("option").each(function () {
if ($(this).text().match(matcher)) {
this.selected = valid = true;
return false;
}
});
if (!valid) {
// remove invalid value, as it didn't match anything
$(this).val("");
select.val("");
input.data("autocomplete").term = "";
return false;
}
}
}
})
.addClass("ui-widget ui-widget-content ui-corner-left");
input.data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
$("<a>")
.attr("tabIndex", -1)
.attr("title", "Show All Items")
.appendTo(wrapper)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("ui-corner-right ui-combobox-toggle")
.click(function () {
// close if already visible
if (input.autocomplete("widget").is(":visible")) {
input.autocomplete("close");
return;
}
// work around a bug (likely same cause as #5265)
$(this).blur();
// pass empty string as value to search for, displaying all results
input.autocomplete("search", "");
input.focus();
});
},
destroy: function () {
this.wrapper.remove();
this.element.show();
$.Widget.prototype.destroy.call(this);
}
});
})(jQuery);
$(function () {
$("#combobox").combobox();
$("#toggle").click(function () {
$("#combobox").toggle();
});
});
</script>
</head>
<body>
<div class="demo">
<div class="ui-widget">
<label>
Your preferred programming language:
</label>
<select id="combobox">
<option value="">Select one...</option>
<option value="ActionScript">ActionScript</option>
<option value="AppleScript">AppleScript</option>
<option value="Asp">Asp</option>
<option value="BASIC">BASIC</option>
<option value="C">C</option>
<option value="C++">C++</option>
<option value="Clojure">Clojure</option>
<option value="COBOL">COBOL</option>
<option value="ColdFusion">ColdFusion</option>
<option value="Erlang">Erlang</option>
<option value="Fortran">Fortran</option>
<option value="Groovy">Groovy</option>
<option value="Haskell">Haskell</option>
<option value="Java">Java</option>
<option value="JavaScript">JavaScript</option>
<option value="Lisp">Lisp</option>
<option value="Perl">Perl</option>
<option value="PHP">PHP</option>
<option value="Python">Python</option>
<option value="Ruby">Ruby</option>
<option value="Scala">Scala</option>
<option value="Scheme">Scheme</option>
</select>
</div>
<button id="toggle">
Show underlying select</button>
</div>
<!-- End demo -->
</body>
</html>
I just found the issue that was causing incorrect rendering in IE. For things to render properly in IE, when using jQuery, you must specify doc type as in code below. That will make the jQuery combobox render properly in IE.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery UI Example Page</title>
<link type="text/css" href="css/cupertino/jquery-ui-1.8.21.custom.css" rel="stylesheet" />
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.21.custom.min.js"></script>
You could, as an alternate, also use the following web URLs to get the css and scripts related to jQuery in this example, rather than the local URLs that were mentioned in above code sample.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery UI Example Page</title>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui
/1.8/themes/cupertino/jquery-ui.css" type="text/css" media="all" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2
/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-
ui.min.js" type="text/javascript"></script>

jqGrid: No such method: restoreRow

I am having an issue working with jaGrid and ASP.NET MVC 2. Everything is working, but when I select a row I get this error on FireBug: uncaught exception: jqGrid - No such method: restoreRow.
Debugin Js I realize that error happend here:
onSelectRow: function(id) {
if (id && id !== lastsel) {
jQuery('#list').jqGrid('restoreRow', lastsel);
jQuery('#list').jqGrid('editRow', id, true);
lastsel = id;
}
I think, the problem is the jqGrid libraries include (or the include order). This is my Index.aspx page.
<%--CSS Files--%>
<link href="/Content/jquery-ui-1.8.7.css" rel="stylesheet" type="text/css" />
<link href="/Content/ui.jqgrid.css" rel="stylesheet" type="text/css" />
<link href="/Content/ui.multiselect.css" rel="stylesheet" type="text/css" />
<%--jQuery Library--%>
<script type="text/javascript" src="../../Scripts/jquery-1.4.4.min.js"></script>
<%--Must load language tag BEFORE script tag--%>
<script type="text/javascript" src="../../Scripts/grid.locale-es.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.jqGrid.min.js"></script>
<script type="text/javascript" src="../../Scripts/grid.jqueryui.js"></script>
<script type="text/javascript" src="../../Scripts/grid.base.js"></script>
<script type="text/javascript" src="../../Scripts/grid.common.js"></script>
<script type="text/javascript" src="../../Scripts/grid.formedit.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.fmatter.js"></script>
<script type="text/javascript" src="../../Scripts/grid.custom.js"></script>
<script type="text/javascript" src="../../Scripts/jqDnR.js"></script>
<script type="text/javascript" src="../../Scripts/jqModal.js"></script>
<script type="text/javascript" src="../../Scripts/grid.import.js"></script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<table id="tableAccidentes" border=0>
<tr>
<td><img alt="" src="../../images/icono_victima.png" /></td>
<td><h2>Accidentes Registrados</h2></td>
</tr>
</table>
<script type="text/javascript">
var lastsel;
var Plantas = ['Pablo Podesta', 'Pilar', 'Tigre', 'Otra'];
jQuery(document).ready(function() {
jQuery("#list").jqGrid({
url: '/Accidentes/ListarAccidentes',
datatype: "json",
colNames: ['Fecha', 'Detalle', 'Accidentado', 'Planta'],
colModel: [
{ name:'Fecha', index:'Fecha', width:150, align:'left',
editable:true },
{ name:'Detalle', index:'Detalle', width:150, align:'left',
editable:true },
{ name:'Accidentado', index:'Accidentado', width:200,
align:'left', editable:true },
{ name:'planta', index:'planta', width:150, align:'left',
editable:true, edittype:"select",
editoptions: { value:Plantas} }
],
onSelectRow: function(id) {
if (id && id !== lastsel) {
jQuery('#list').jqGrid('restoreRow', lastsel);
jQuery('#list').jqGrid('editRow', id, true);
lastsel = id;
}
},
editurl: "/Accidentes/GridSave",
edit: {
addCaption: "Agregar Accidente",
editCaption: "Editar Accidente",
bSubmit: "Guardar",
bCancel: "Cancelar",
bClose: "Cerrar",
saveData: "Se modifico el registro! ¿guardar los cambios?",
bYes: "Si",
bNo: "No",
bExit: "Cancelar"
},
pager: jQuery('#pager'),
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'Id',
sortorder: "desc",
viewrecords: true,
imgpath: '/scripts/themes/coffee/images',
caption: 'Accidente'
}).navGrid('#pager', { edit: true, add: true, search: false, del: false },
{ closeAfterAdd: true, closeAfterEdit: true });
// add custom button to export the data to excel
jQuery("#list").jqGrid('navButtonAdd','#pager',{
caption:"",
onClickButton : function () {
jQuery("#list").jqGrid('excelExport',
{ url: '/Accidentes/ExportarAccidentes' });
}
});
});
</script>
<%-- HTML Required--%>
<table id="list" class="scroll" cellpadding="0" cellspacing="0"></table>
<div id="pager" class="scroll" style="text-align:center;"></div>
Please, can someone help me?
The restoreRow and editRow methods, which you use, are defined in the grid.inlinedit.js file and are the part of the inline editing module (see more in the jqGrid documentation). Moreover you should remove the file jquery.jqGrid.min.js to avoid having definitions of the same functions twice. Because the method restoreRow was not defined in the jquery.jqGrid.min.js which you use you use probably wrong downloaded jqGrid version. You should download the jqGrid one more time and be sure that you check "Inline Editing" module. If you open jquery.jqGrid.min.js file in the text editor you will see in the comment at the begining of the file all modules which was the part of the download.
Some additional small remarks: in the documentation is described which parameters of the colModel are default. For example, width:150 and align:'left' have defaout values, so you can remove there from the column definition.
The value property for "select" type of the editoptions which you use is wrong. The Plantas should be defined as
var Plantas = { 'Pablo Podesta':'Pablo Podesta', Pilar:'Pilar',
Tigre:'Tigre', Otra:'Otra'};
or as
var Plantas = 'Pablo Podesta:Pablo Podesta;Pilar:Pilar;Tigre:Tigre;Otra:Otra';
See the documentation for details.
The parameter imgpath is deprecated and should be removed. Class "scroll" is also deprecated and the HTML fragment for the jqGrid can be reduced to
<table id="list"></table>
<div id="pager"></div>
See an example here.
The parameter edit is not exist in the jqGrid it is the parameter of editGridRow from the form editing. You can define it as the part of navGrid parameters prmEdit and prmAdd. Currently you use only prmEdit. Probably the usage of grid.locale-XX.js from the i18n directory will make the usage of edit parameter unneeded.

Resources