Jquery Autocomplete display names and send Id - javascript

How can I change my jQuery autocomplete to use an Id instead of my values?
I would like to display the list of names but send a search using the Id value. Now it is working properly with the names but I think it will be more effective if it tries to find a unique value as an ID.
$.getJSON('Dashboard/CompaniesWithId', function (data) {
$.each(data, function (i, item) {
sellers[i] = item.Name;
sellersID[i] = item.Id;
});
}).error(function () {
console.log("error loading seller to the autocomplete");
});
$("#searchSeller").autocomplete({
messages: {
noResults: 'No sellers with this name',
},
minLength: 2,
delay: 500,
source: sellers,
});

you can add a hidden field and use the on select event to set the value of the hidden field to the selected id
http://api.jqueryui.com/autocomplete/#event-select
you can also use selection data with format [{value: 'value', label: 'label'}] but using this way, the field will show the id instead of the label
var availableTags = [
{id: 1, label: "ActionScript"},
{id: 2, label: "Ruby"},
{id: 3, label: "Scala"},
{id: 4, label: "Scheme"}
];
availableTags2 = [
{value: 1, label: "ActionScript"},
{value: 2, label: "Ruby"},
{value: 3, label: "Scala"},
{value: 4, label: "Scheme"}
];
$( "#a" ).autocomplete({
source: availableTags,
select: function( event, ui ) {
$('#tosend').val(ui.item.id);
}
});
$( "#b" ).autocomplete({
source: availableTags2
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script
src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"
integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU="
crossorigin="anonymous"></script>
id to send<br>
<input type="text" name="tosend" id="tosend"><br><br>
type below<br>
<input id="a"><br>
<br>
<br>
using value instead of id<br>
<input id="b">

I don't know anything about your back-end. But assuming it is accepting IDs for your search parameters, will changing the source value to sellersID resolve your issue? You also have that extra comma after sources. It will cause you problems.
$("#searchSeller").autocomplete({
messages: {
noResults: 'No sellers with this ID.',
},
minLength: 2,
delay: 500,
source: sellersID
});

Related

Control DataTables columns visibility with checkboxes

I am using datatables to dynamically render a table on my blade template. I have a series of checkboxes that user can check to show/hide table columns. All of this is working great.
This is what my template looks like:
template.blade.php
<table id="dataTables-report" class="table table-striped table-bordered table-hover">
</table>
Here is what I am using to render the table:
scripts.js
$('#dataTables-report').DataTable({
...
columnDefs: [
{
targets: 0,
title: 'Name',
searchable: true,
data: function (row, type, val, meta) {
// return row.data;
}
},
#if($report->order_date)
{
targets: 1,
title: 'Order Date',
searchable: false,
data: function (row, type, val, meta) {
// return row.data;
}
},
#endif
#if($report->order_number)
{
targets: 2, // could be 1 if order date is not selected
title: 'Order Number',
searchable: false,
data: function (row, type, val, meta) {
// return row.data;
}
},
#endif
...
});
"Order Date" is a checkbox that a user can choose to display on the table. If it is checked, it shows that column. Otherwise it does not.
It is possible that a different column could be selected first and it could be targets: 1. Now if a user checks another box, targets needs to dynamically get set to the next number. In this case: targets: 2.
Each checkbox is stored as it's own column in the database, so I don't think I can do any sort of loop (hence a bunch of if statements). Otherwise, I think something like this would work.
Is there a way to dynamically generate the targets number right in my blade template?
If you're seeking truly dynamic column visibility controlled by checkboxes (as I understood your ultimate goal), it can be done user-end entirely by few lines of jQuery.
In order to do that, you may simply
append source object property of each column as a value attribute to your <input> nodes:
upon change event, find the column that is sourced (using column().dataSrc() method) by the object property that corresponds to clicked checkbox value and adjust that column visibility (using .column().visible() method accordingly:
$('#checkboxWrapper').on('change', '[type="checkbox"]', event => {
let colindex = null;
dataTable.columns().every(function(){
if(this.dataSrc() == $(event.target).val()) colindex = this.index();
});
dataTable.column(colindex).visible($(event.target).prop('checked')).draw();
});
Complete live demo of that concept you may find below:
//sample source data
const dataSrc = [
{id: 1, item: 'apple', cat: 'fruit'},
{id: 2, item: 'carrot', cat: 'vegie'},
{id: 3, item: 'banana', cat: 'fruit'}
];
//extract all unique object keys from data source array
const checkboxes = [...new Set(dataSrc
.map(item => Object.keys(item))
.flat())];
//translate those into <input> nodes HTML
const checkboxesHtml = checkboxes.reduce((inputs, prop) => inputs += `<input type="checkbox" value="${prop}" checked>${prop}</input>`,'');
$('#checkboxWrapper').append(checkboxesHtml);
//initialize datatables
const dataTable = $('#example').DataTable({
data: dataSrc,
dom: 't',
columns: checkboxes.map(prop => ({title: prop, data: prop}))
});
//control columns visibility with checkboxes
$('#checkboxWrapper').on('change', '[type="checkbox"]', event => {
//grab column().index() that corresponds to checkbox value
let colindex = null;
dataTable.columns().every(function(){
if(this.dataSrc() == $(event.target).val()) colindex = this.index();
});
//toggle selected column visibility
dataTable.column(colindex).visible($(event.target).prop('checked')).draw();
});
<!doctype html>
<html>
<head>
<script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<div id="checkboxWrapper"></div>
<table id="example"></table>
</body>
</html>
Thank you for your suggestions, here is what I came up with as a "quick" solution while I look further into your recommendations.
In my blade template, I created a global variable that I could access within my php.
#section('scripts')
<script>
$(function () {
...
let columnTarget = 0;
...
$('#dataTables-report').DataTable({
...
columnDefs: [
{
targets: columnTarget,
title: 'Name',
searchable: true,
data: function (row, type, val, meta) {
// return row.data;
}
},
#if($report->order_date)
{
targets: ++columnTarget,
title: 'Order Date',
searchable: false,
data: function (row, type, val, meta) {
// return row.data;
}
},
#endif
#if($report->order_number)
{
targets: ++columnTarget,
title: 'Order Number',
searchable: false,
data: function (row, type, val, meta) {
// return row.data;
}
},
#endif
...
</script>
#endsection
This seems to work well; correctly (dynamically) assigning the targets value.
->addColumn('action', function ($floor) {
$action=
#Can("floor-edit"){"
<a class='btn btn-info btn-sm'
href=".route("floor.edit",Crypt::encrypt($floor->id))."><i class='fa fa-edit'></i>
</a>
<button type='button' name='delete' id=".Crypt::encrypt($floor->id)." class='delete btn btn-danger btn-sm'><i class='fa fa-trash'></i></button>
"};
return $action;
})

Remove selected option from select2 multiselect on change.

I have the following code. The aim is to style a select2 box with textbox as the searchbox. So I have implemented it as multiselect , but I only want one option to be selected.
One option is to restrict using maximumSelectionLength: 1. But in this case the limit message will be shown which i do not want to happen. (Even if i hide it some space will be taken up ).
Other option is to hide everything other than last-child , in that case multiple values will be send to backend when form is submitted.
So is there a way to remove the currently selected value when the new value is selected in multiselect ?
I'm using select2 version 3.5.2
$('#placeSelect').select2({
width: '100%',
allowClear: true,
multiple: true,
placeholder: "Click here and start typing to search.",
data: [
{ id: 1, text: "Honolulu" },
{ id: 2, text: "Tokyo" },
{ id: 3, text: "Delhi" },
{ id: 4, text: "Zurich" }
]
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/select2/3.4.8/select2.js"></script>
<link href="http://cdn.jsdelivr.net/select2/3.4.8/select2.css" rel="stylesheet"/>
<h3>Select a value</h3>
<input type="text" id="placeSelect"/>
You can only keep the last selected item and remove all other. Like this way :
$('#placeSelect').click(function () {
var t = $("#placeSelect").val().substr($("#placeSelect").val().length - 1);
$("#placeSelect").val(t).trigger("change");
});
$('#placeSelect').select2({
width: '100%',
allowClear: true,
multiple: true,
placeholder: "Click here and start typing to search.",
data: [
{ id: 1, text: "Honolulu" },
{ id: 2, text: "Tokyo" },
{ id: 3, text: "Delhi" },
{ id: 4, text: "Zurich" }
]
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/select2/3.4.8/select2.js"></script>
<link href="http://cdn.jsdelivr.net/select2/3.4.8/select2.css" rel="stylesheet"/>
<h3>Select a value</h3>
<input type="text" id="placeSelect"/>
$('#placeSelect').select2({
width: '100%',
allowClear: true,
multiple: false,
placeholder: "Click here and start typing to search.",
data: [
{ id: 1, text: "Honolulu" },
{ id: 2, text: "Tokyo" },
{ id: 3, text: "Delhi" },
{ id: 4, text: "Zurich" }
]
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/select2/3.4.8/select2.js"></script>
<link href="http://cdn.jsdelivr.net/select2/3.4.8/select2.css" rel="stylesheet"/>
<h3>Select a value</h3>
<input type="text" id="placeSelect"/>
You are using a multi option select, I suggest you to do the following:
multiple: false,
just add the following code in your query and it will work as you need it
$('ul.select2-choices').on("click", function() {
$("ul.select2-choices li .select2-search-choice-close").click();
});

Dgrid - Display label for number (i.e. 02 = Cat) I want to display Cat - not the number

In my Dgrid I have a column that displays the code (in number format) for an event.
enter image description here
I want to display the label not the number in the dgrid. So if 1 = Cat. In the database it shows as a 1 - but I want to display 'Cat' in dgrid. Can't find anything on how to do this.
Help or a lead in a direction would be helpful. Thanks!!
UPDATED: 6.16.15
Here is the code. I'm limited in what I can show.
These are some of the codes. 02 = XXXXX, 03 = XXXXX1, and so on and so on. Right now, the dgrid displays the numbers. It's kind of like a key. I need it to display what the number represents in the dgrid, not the number. So 02 should display 'Traffic Stop'. Not sure how to do a jsfiddle yet, and don't have a whole lot of extra time at the moment. I'm limited in what info I can give out, so I'd have to recreate a dummy version.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>XXXXXXXX Events</title>
<link rel="stylesheet" href="/static/web_ui/dgrid/css/skins/slate.css">
<h1>XXXXXXXX Events</h1>
<form id="queryForm">
<label for="XXXXXField">XXXXX Type contains:</label>
<input id="XXXXXField" name="event_type">
<button type="submit">Filter</button>
<button type="reset">Reset</button>
</form>
<script src="/static/web_ui/dojo/dojo.js"
data-dojo-config="async: true"></script>
<script>
require([
'dojo/_base/declare',
'dojo/dom',
'dojo/on',
'dstore/Rest',
'dstore/Request',
'dgrid/extensions/ColumnResizer',
'dgrid/extensions/ColumnReorder',
'dgrid/CellSelection',
'dgrid/extensions/DijitRegistry',
// 'dstore/Memory',
// 'dstore/Trackable',
// 'dstore/Cache',
'dgrid/OnDemandGrid'
// 'dojo/domReady!'
], function (declare, dom, on, Rest, Request, ColumnResizer, ColumnReorder, CellSelection, DijitRegistry, OnDemandGrid) {
var store = new Rest({target:'/api/XXXXXXEvents/?format=json',
sortParam: 'ordering', ascendingPrefix:'', descendingPrefix:'-'
});
// var cacheStore = Cache.create(store, {
// cachedStore: new (Memory.createSubclass(Trackable)) ()
// });
var grid = window.grid = new (declare([OnDemandGrid, ColumnResizer, ColumnReorder, CellSelection, DijitRegistry])) ({
collection: store,
selectionMode: 'single',
sort: 'id',
// idProperty: 'id',
columns: [
{field: 'id', label:'ID', resizeable: false},
{field: 'XXXXX_type', label:'XXXXX Type', resizeable: false},
{field: 'XXXXX_at', label:'XXXXX Time', resizeable: false},
{field:'XXXXX', label:'XXXXX Count', resizeable: false},
{field:'XXXXX', label:'XXXXX', resizeable: false},
{field:'XXXXX_info', label:'XXXXX Info', resizeable: false},
{field:'hidden', label:'Hidden', resizeable: false},
{field:'XXXXX', label:'XXXXX', resizeable: false},
{field:'XXXXX', label:'XXXXX', resizeable: false}
]
}, 'grid');
grid.startup();
on(dom.byId('queryForm'), 'submit', function(event) {
event.preventDefault();
grid.set('collection', store.filter({
// Pass a RegExp to Memory's filter method
// Note: this code does not go out of its way to escape
// characters that have special meaning in RegExps
last: new RegExp("^\d+$")
}));
});
on(dom.byId('queryForm'), 'reset', function() {
// Reset the query when the form is reset
grid.set('collection', store);
});
});
</script>
</head>
<body class="slate">
<div id="grid"></div>
</body>
</html>
You need to use the column formatter function for rendering data.
check the jsfiddle over here.
Check the examples over here
I have taken this example and modified as per your needs.
require([
'dgrid/Grid',
'dojo/domReady!'
], function(Grid) {
var data = [
{ id: 1, number: 7 },
{ id: 2, number: 8 },
{ id: 3, number: 9 }
];
function testFormatter(item){
//console.log(item,typeof(item));
var newItem;
if ( item == 7 )
newItem = 'Dog'
else if ( item == 8 )
newItem = 'Cat'
else if ( item == 9 )
newItem = 'Bird'
return newItem;
}
var columnsFormatter = [
{
label: "Number",
field: "number",
formatter: testFormatter
}
];
var grid = new Grid({
columns: columnsFormatter
}, "gridcontainer");;
grid.renderArray(data);
});

EmberJS - Checkboxes and Getting Values in Controller

Below is a simple example how I intend to use check boxes. What I have is an array of terms with id and name field and each post can be assigned to a single or multiple terms/categories.
var config = {};
config.terms = [
{id: 1, termName: 'Red'},
{id: 2, termName: 'Green'},
{id: 3, termName: 'Blue'}
];
Problem
With EmberJS handlebar expression I am showing those checkboxes but I am confused what to use as form element variable name field doesn't seem to defined in the controller. The checked field works as controller property but when I add termName as checked all of the checkboxes are checked by default and label after checking changes after clicking checkboxes.
What I need to get on the controller is the term names that are selected
Below is the example code. You can also find it on JsFiddle. Check uncheck the red/green/blue checkboxes to see the problem. Also have a look in console.
HTML
<div id="main"></div>
<script type="text/x-handlebars" data-template-name="index">
{{#each term in terms}}
{{input type="checkbox" name=term.name}} {{term.name}}
{{/each}}
<button {{action "submit"}}>Submit</button>
</script>
JS
var config = {};
config.terms = [
{id: 1, name: 'Red'},
{id: 2, name: 'Green'},
{id: 3, name: 'Blue'}
];
App = Ember.Application.create({
rootElement: '#main'
});
App.IndexRoute = Ember.Route.extend({
setupController: function(controller){
controller.set('terms', config.terms);
}
});
App.IndexController = Ember.Controller.extend({
actions: {
submit: function(){
console.log(this.Red);
console.log(this.Blue);
console.log(this.Green);
}
}
});
In you jsfiddle example you'r binding the name to the checked value of the checkbox. I think that's not what you want to do.
The checked value should be bound to a boolean value.
So,
1st approach: either add a property to your term object (selected: false)
config.terms = [
{id: 1, name: 'Red', selected: false },
{id: 2, name: 'Green', selected: false },
{id: 3, name: 'Blue', selected: false }
];
(as Ember objects:)
config.terms = [
Em.Object.create({id: 1, name: 'Red', selected: false }),
Em.Object.create({id: 2, name: 'Green', selected: false }),
Em.Object.create({id: 3, name: 'Blue', selected: false })
];
and then bind the property in your template this way:
{{input type="checkbox" checked=term.selected}}
2nd approach: bind it to controller properties:
// inside your controller:
redSelected: false,
greenSelected: false,
blueSelected: false,
{{input type="checkbox" checked=controlller.redSelected}}

Getting the result suggestion list in jquery autocomplete

I'm using the jquery autocomplete plugin and I am comming up to a few problems:
I have a lot of data and when I type data a long suggestion list is shown and a scrollbar is needed:
$("#txtName").autocomplete(data,
{ matchContains: true,
minChars: 0,
max: 3000,
scroll: true,
//scrollHeight: 180,
width: 200
});
but, the scrollbar does't work properly in IE (it's a known issue, I searched alot but have'nt found a relevant solution).
so I decided to block the suggestion list popup and get the suggestion list results into an array or somthing similar and show them in my control.
my problem is - How do I get that list?
Thanks in advance!
Quickly looking through that Plugin's API, I don't see any events that let you handle the response from a server call-back. You may want to switch and use the official JQuery UI library for your auto-completing needs. There is an appendTo option that might suit your need.
I found the answer (part of it, I still need to work on it).
I'll first post the code and then explain it:
$(function ()
{
var names = [
{ label: 'Java', value: '1' },
{ label: 'C++', value: '2' },
{ label: 'C#', value: '3' },
{ label: 'Jquery', value: '4' },
{ label: 'Javascript', value: '5' },
{ label: 'ASP', value: '6' },
{ label: 'Pearl', value: '7' },
{ label: 'VB', value: '8' },
{ label: 'Ajax', value: '9' },
{ label: 'Json', value: '10' }];
$("#txtName").autocomplete({
minLength: 2,
source: names,
delay: 500
}).data("autocomplete")._renderItem = function (ul, item)
{
//add data to my control, need to take care of earasing each time.
var elOptNew = document.createElement('option');
elOptNew.text = item.label;
elOptNew.value = item.value;
lst.add(elOptNew);
//this code here adds the items to the popup thats built in.(it's written in jquery-ui.min.js)
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
});
Html:
<input id="txtName"/>
<select id="lst" size='10'></select>
The added part (_renderItem) adds one item each time, so you can do whatever you want to do with an item. I decided to add it to a list.
The other thing that's not done is erasing the list each time. I still need to figure out how to do that.

Categories

Resources