Why select2 filter function doesn't work when i take the options from json - jquery-select2

Halo, i'm new to javascript, i'm using select2, i take the options from desproducts.php which return json containing product list. The product list is shown, but the filter function doesn't work, here is the image
here is my code :
$('.select2-show-search').select2({
minimumResultsForSearch: '',
allowClear: true,
ajax: {
url: 'desproducts.php',
dataType: 'json',
processResults: function (data) {
return {
results: data
};
},
}
});
i have found a sloution, i take the options directly from database using this code :
<select class="form-control select2-show-search">
<option value=""></option>
<?php foreach ($desproducts as $desproduct): ?>
<option value="<?= $desproduct["desProductID"] ?>" harga="<?=
$desproduct["desProductPrice"] ?>"><?= $desproduct["desProductName"] ?>
</option>
<?php endforeach; ?>
</select>
and this is the code in javascript
$('.select2-show-search').select2({
minimumResultsForSearch: '',
allowClear: true,
});

Related

Equivalent script of Datatable in angular ui grid [duplicate]

I created a Single HTML - Table - With Export Options, Search, Pagination using Static Data using DataTables.
plnkr.co/edit/n3cbx8GrGoJtOpgbxE32?p=preview
is similar kind of example or working html available in angular-ui-grid
Datatable doesn't works well with huge records. Could you please kindly help with an equivalent html file using angular ui grid..thanks in advance for anything
Thanks.
From what it looks like, you are able to export CSV and PDF. I don't see any evidence of the Excel export working. I am not sure offhand on the print function, however, exporting the PDF and printing would be an option. I can look later if it's a deal breaker.
The JS code is pretty straight forward. I've added some options for the PDF configuration as well.
The code for the exporting function comes verbatim from UI-Grid.info: 312 Exporting Data With Custom UI. It could be converted to buttons if you wanted, but this provides the external export functionality. The little menu in the upper right corner also has these export options, so I've left it for your experimentation. Setting $scope.gridOptions.enableGridMenu to false will turn that off.
JS
$scope.gridOptions = {
enableGridMenu: true,
data: 'data',
paginationPageSizes: [10],
paginationPageSize: 10,
exporterLinkLabel: 'get your csv here',
exporterPdfDefaultStyle: {fontSize: 9},
exporterPdfTableStyle: {margin: [10, 10, 10, 10]},
exporterPdfTableHeaderStyle: {fontSize: 10, bold: true, italics: true, color: 'red'},
exporterPdfOrientation: 'portrait',
exporterPdfPageSize: 'LETTER',
exporterPdfMaxGridWidth: 500,
onRegisterApi: function(gridApi){
$scope.gridApi = gridApi;
},
};
// Verbatim: http://ui-grid.info/docs/#/tutorial/312_exporting_data_complex
$scope.export = function(){
if ($scope.export_format == 'csv') {
var myElement = angular.element(document.querySelectorAll(".custom-csv-link-location"));
$scope.gridApi.exporter.csvExport( $scope.export_row_type, $scope.export_column_type, myElement );
} else if ($scope.export_format == 'pdf') {
$scope.gridApi.exporter.pdfExport( $scope.export_row_type, $scope.export_column_type );
}
};
HTML
<!-- Verbatim: http://ui-grid.info/docs/#/tutorial/312_exporting_data_complex -->
<label>Which columns should we export?</label>
<select ng-model="export_column_type"</select>
<option value='all'>All</option>
<option value='visible'>Visible</option>
</select>
<label>Which rows should we export?</label>
<select ng-model="export_row_type"</select>
<option value='all'>All</option>
<option value='visible'>Visible</option>
<option value='selected'>Selected</option>
</select>
<label>What format would you like?</label>
<select ng-model="export_format"</select>
<option value='csv'>CSV</option>
<option value='pdf'>PDF</option>
</select>
<button ng-click="export()">Export</button>
<div class="custom-csv-link-location">
<label>Your CSV will show below:</label>
<span class="ui-grid-exporter-csv-link">&nbsp</span>
</div>
<div ui-grid="gridOptions" class="grid" style="width:100%"
ui-grid-selection ui-grid-exporter ui-grid-pagination></div>
</div>
Example Plunk

Select2 custom data return from API

I am working with select2 to display the data return from the API. However, the data didn't manage to load out.Am I doing something wrong? Any ideas how to fix this?
HTML:
<select class="js-example-basic-single form-control select2 select2-hidden-accessible" id="user" name="user_id" autocomplete="off" required="required">
<option value="">Please select</option>
</select>
script:
var url = "{{env('API_URL')}}";
var username = null;
$(".select2").select2({
placeholder: "Please select",
width: null,
ajax: {
dataType: "jsonp",
method: "GET",
data: function (term) {
username = term.term;
return {"username": username};
},
url: url+"user/search/username?",
results: function (data) {
return {
results: data.result.users
};
},
},
formatResult: function (option) {
return "<option value='" + option.id + "'>" + option.username + "</option>";
},
formatSelection: function (option) {
return option.id;
}
});
result return from API:
result : [{"users":["[object] (App\\User: {\"username\":\"Kaki\",\"id\":123456})","[object] (App\\User: {\"username\":\"(Alan)\",\"id\":123457})","[object] (App\\User: {\"username\":\"Alex\",\"id\":123458})","[object] (App\\User: {\"username\":\"Sky\",\"id\":1234569})","[object] (App\\User: {\"username\":\"Kvin\",\"id\":123460})"]}] []
One thing is your JSON return from API who is not well formatted.
[{
"users":[
"[object] (App\\User: {\"username\":\"Kaki\",\"id\":123456})",
"[object] (App\\User: {\"username\":\"(Alan)\",\"id\":123457})",
...
]
}]
should be
[{
"users":[
{"username":"Kaki","id":123456}),
{"username":"(Alan)","id":123457}),
...
]
}]
I don't know what is Select2 version you use, but > 4 is advice.
Use functions templateResult and templateSelection is better, later you can return HTML for nicer rendering.
You can use this snipplet demo.
$(".select2").select2({
placeholder: "Please select",
width: null,
ajax: {
dataType: "json",
method: "GET",
url: function (params) {
// return 'url+"user/search/username?' + params.term;
// Fake url to make demo working, use upper line
return 'http://ip.jsontest.com/';
},
processResults: function (data) {
// Use this function to convert api result to Select2 result
// return {"results":data.users};
// Build fake answer for demo
return {"results":[{"username":"Kaki","id":123456},{"username":"(Alan)","id":123457}]};
},
},
templateResult: function (dataRow) {
if (dataRow.loading) return dataRow.text;
return dataRow.username;
},
templateSelection: function (dataRow) {
return dataRow.username;
}
});
.select2 {
width:50%
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/select2/4.0.1/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/select2/4.0.1/js/select2.full.js"></script>
<select class="form-control select2" id="user_id" name="user_id" autocomplete="off" required="required">
<option value="">Please select</option>
</select>
$(".select2").select2({
placeholder: "Please select",
width: null,
ajax: {
dataType: "json",
method: "GET",
url: function (params) {
// return 'url+"user/search/username?' + params.term;
// Fake url to make demo working, use upper line
return 'http://ip.jsontest.com/';
},
processResults: function (data) {
// Use this function to convert api result to Select2 result
// return {"results":data.users};
// Build fake answer for demo
return {"results":[{"username":"Kaki","id":123456},{"username":"(Alan)","id":123457}]};
},
},
templateResult: function (dataRow) {
if (dataRow.loading) return dataRow.text;
return dataRow.username;
},
templateSelection: function (dataRow) {
return dataRow.username;
}
});
.select2 {
width:50%
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/select2/4.0.1/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/select2/4.0.1/js/select2.full.js"></script>
<select class="form-control select2" id="user_id" name="user_id" autocomplete="off" required="required">
<option value="">Please select</option>
</select>

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();
});
}

Multiple Autocomplete box using same Ajax

I want to have two different Autocomplete boxes but both using the same AJAX method in the background.
Here is my script
$(document).ready(function () {
$("#SearchProject")
.each(function () {
var urlloc = "/Project/FindProjects";
$(this).autocomplete({
source: function (request, response) {
$.ajax({
url: urlloc, type: "POST", dataType: "json",
data: { searchString: request.term, maxResults: 10 },
success: function (data) {
response($.map(data, function (item) {
return { label: item.name, value: item.name, id: item.id }
}))
}
})
},
select: function (event, ui) {
$("[id$='ProjectID']").val(ui.item.id);
// alert(ui.item ? ("You picked '" + ui.item.label + "' with an ID of " + ui.item.id)
// : "Nothing selected, input was " + this.value);
}
});
});
});
I want my input fields on the form as below.
<input id="SearchProject" name="SearchProject" type="text" value="" /><input type="hidden" name="ProjectID" id="ProjectID" value="" />
<input id="SearchProject2" name="SearchProject" type="text" value="" /><input type="hidden" name="ProjectID" id="ProjectID2" value="" />
When autocomplete select is complete I want the corresponding hidden field to be updated.
How do i achieve this?
Two possibilities:
First (the one I prefer): extract your auto-complete setup into a method:
function configureAutocomplete(autoField, updatedField)
You call this method for as many auto-complete fields as you want, passing it two JQuery selectors: the selector for the auto-complete field, and the hidden update field.
The other way is to base the ID of the hidden field on that of the auto-complete field. This will let you use an each to attach behavior to the fields, but I think it' more trouble than it's worth.

JQuery selectmenu won't initialize after ajax call

I am using filamentgroup JQuery selectmenu widget. The widget is initialized in page's head section. When the page is loaded for the first time Jquery loads widget successfully but after ajax call (form submit using POST) selectmenu widget stops working (not initializing). I had same problem using input text fields for submitting form on enter key press but then I used delegate method to attach an event handler to selected elements. And it worked. So my question is: how can I reinitialize selectmenu after AJAX call. Maybe I can use same delegate method for initialization. I googled but didn't found any JQuery events that initializes widgets. Here is the code snippet
<head>
<script type="text/javascript">
$(document).ready(function()
{
$('select').selectmenu
({
width: 70,
style: 'dropdown',
menuWidth: 100,
maxHeight: 400,
change: function()
{
$(this).parents('form').submit();
}
});
$('body').delegate('.submit', 'keydown', function(e)
{
if (e.keyCode == 13)
{
$(this).parents('form').submit();
return false;
}
});
$('#regFormID').submit(function()
{
$.ajax(
{
type: 'POST',
url: 'index.php',
data: $(this).serialize(),
error: function(xml, status, error)
{
$('#dataFilterID').html('<p><strong>Error Code:</strong> '+status+'</p><p><strong>Explanation:</strong> '+error+'</p>');
},
success: function(data, textStatus, jqXHR)
{
$('#dataTableID').html($(data).find('#dataFilterID').html());
}
});
return false;
}
});
</script>
</head>
<body>
<div id="#dataFilterID">
<form id="regFormID" class="reg-form" name="regForm" method="POST" action="">
<select class="select" id="Filter-dbPage-count" name="Filter-dbPage-count">
<option selected="selected" value="30">30</option>
<option value="50">50</option>
<option value="100">100</option>
<option value="150">150</option>
<option value="200">200</option>
</select>
<input type="text" value="" class="submit " id="Filter-dbField-1" name="Filter-dbField-1">
<input type="text" value="" class="submit " id="Filter-dbField-2" name="Filter-dbField-2">
<input type="text" value="" class="submit " id="Filter-dbField-3" name="Filter-dbField-3">
</form>
</div>
</body>
rebind in the success callback
success: function(data, textStatus, jqXHR)
{
$('#dataTableID').html($(data).find('#dataFilterID').html());
$('select').selectmenu
({
width: 70,
style: 'dropdown',
menuWidth: 100,
maxHeight: 400,
change: function()
{
$("select").parents('form').submit();
}
});
}

Resources