Error "Object does not support property or method 'selectize'" on selectize initialization - selectize.js

i'm triyng to use this code
$(this.node).find("select").selectize({
valueField: "value",
labelField: "label",
searchField: ["label"],
maxOptions: 10,
create: false,
render: {
option: function (item, escape) {
return "<div>" + escape(item.label) + "</div>";
}
},
load: function (query, callback) {
if (!query.length) return callback();
$.ajax({
url: "../ajaxPage.aspx?functionName=GET_03&fieldValue=" + encodeURIComponent(query),
type: "POST",
dataType: "json",
data: {
maxresults: 10
},
error: function () {
callback();
},
success: function (res) {
console.log(res);
callback(res);
}
});
}
});
$(this.node).find("select") is a simple select:
<select name="tagName" id="tagId"></select>
I include this js in my page:
microplugin.min.js
sifter.min.js
selectize.js
selectize.default.css
but when i use .selectize i get this error at runtime:
"Object does not support this property or method selectize"
Any idea about this error?

yes... i'm using jQuery.
I load dependencies in this order:
microplugin.min.js
sifter.min.js
selectize.js
selectize.default.css
do you think is this the wrong order?

You may have to include the css before all the js files.
selectize.default.css
microplugin.min.js
sifter.min.js
selectize.js

Related

Why is displayStart (Datatable 1.10) not working for me?

I am using Datable (1.10.3) and whatever value I set in the diplayStart field, the start parameter of the server request always goes as 0.
Here is my code:
this.table = $('#table').DataTable({
displayStart: 100,
order: [[0, 'desc']],
processing: true,
serverSide: true,
searching: true,
pageLength: 50,
searchDelay: 1000,
language: {
lengthMenu: 'Show _MENU_ records per page'
},
dom: '<"top"il>rt<"bottom"p><"clear">',
ajax: {
url: <url>,
type: 'POST',
headers: {
authorization: <token>
},
data: function (d) {
//setting request data
},
dataSrc: (json) =>{
return json.data;
},
error: function (xhr, error, thrown) {
if (xhr.status + '' === '401') {
location.href = '/';
}
}
},
columns: this.getColumns(),
drawCallback: function () {
//some operations
}
});
It seems to work fine if I initialise the table like the older version, like this:
this.table = $('#table').dataTable({...
But this initialisation breaks other preexisting function calls (like search and row) in the code.
Can anyone suggest where I am going wrong and how can I fix this?
I am not sure if displayStart works with server side.
I realize this is not an ideal solution if you dont find any other you can override the pipeline method forcing it to use whatever you want:
$.fn.dataTable.pipeline = function ( opts ) {
return function ( request, drawCallback, settings ) {
request.start = 20;
return $.ajax( {
"type": opts.method,
"url": opts.url,
"data": request,
"dataType": "json",
"success": drawCallback
} );
}
};
Taken the example from: https://datatables.net/examples/server_side/pipeline.html

Cannot Get Typeahead.js Working with MVC 5 Over Remote

I have no idea what I'm doing wrong, but I cannot get typeahead working in my MVC 5 application. I installed everything via NuGet and my view includes #Scripts.Render("~/bundles/typeahead"), which is rendering properly when viewing the source of the view. So the issue isn't that the dependencies are missing.
I am not seeing any drop down appear when I start typing, and using Fiddler I do not see any calls being made out to the remote that I setup that pulls the data.
Here's the line in my view that typeahead is being attached:
#Html.TextBoxFor(m => m.MainInfo.CompanyName,
new { #class = "form-control typeahead", id = "comp-name", autocomplete="off" })
Here's the portion of my script that configures typeahead and bloodhound:
$(document).ready(function() {
var clients = new Bloodhound({
datumTokenizer: function (datum) {
return Bloodhound.tokenizers.whitespace(datum.value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: "/info/client?like=%QUERY",
wildcard: '%QUERY',
filter: function (clients) {
return $.map(clients, function (client) {
return {
value: client.Name,
clientId: client.Identifier
};
});
}
}
});
clients.initialize();
$('#comp-name').typeahead(null,
{
display: 'value',
minLength: 1,
source: clients.ttAdapter(),
templates: {
empty: "Looks like a new client...",
suggestion: Handlebars.compile("<p><b>{{value}}</b> - {{clientId}}</p>")
}
});
});
Is there something that I've configured wrong in my javascript? I've used a few tutorials as well as their own documentation, but I cannot figure out what I'm doing wrong here. It almost feels like it's not properly initialized, but there are no errors being thrown.
NOTE: Just as an FYI I'm using Bootstrap 3 as well in case that changes anything.
EDIT: Here's my #section Scripts:
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/typeahead")
<script src="#Url.Content("~/Scripts/handlebars.min.js")"></script>
<script src="#Url.Content("~/Scripts/ProjectSetupFormScripts.js")"></script> <-- this is where typeahead is set up
This did the trick for me:
JS
#section Scripts {
<script type="text/javascript">
$(function () {
SetupTipeahead();
});
function SetupTipeahead() {
var engine = new Bloodhound({
remote: {
url: '/Employees/AllEmployees',
ajax: {
type: 'GET'
}
},
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace(d.FullName);
},
queryTokenizer: Bloodhound.tokenizers.whitespace
});
engine.initialize();
$('#FullName').typeahead(null, {
displayKey: 'FullName',
source: engine.ttAdapter(),
templates: {
empty: [
'<div class="empty-message">',
'No match',
'</div>'
].join('\n'),
suggestion: function (data) {
return '<p class="">' + data.FullName + '</p><p class="">' + data.ManNumber + '</p>';
}
}
});
}
</script>
EmployeesController has the following JsonResult
public JsonResult AllEmployees()
{
return Json(db.Employees.ToList(),JsonRequestBehavior.AllowGet);
}
Hello try to wrap your script in #section scripts {} this will place the script at the bottom just before the </body> tag and make sure you are not calling the function before your bundles load.
#section scripts {
<script>
$(document).ready(function() {
var clients = new Bloodhound({
datumTokenizer: function (datum) {
return Bloodhound.tokenizers.whitespace(datum.value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: "/info/client?like=%QUERY",
wildcard: '%QUERY',
filter: function (clients) {
return $.map(clients, function (client) {
return {
value: client.Name,
clientId: client.Identifier
};
});
}
}
});
clients.initialize();
$('#comp-name').typeahead(null,
{
display: 'value',
minLength: 1,
source: clients.ttAdapter(),
templates: {
empty: "Looks like a new client...",
suggestion: Handlebars.compile("<p><b>{{value}}</b> - {{clientId}}</p>")
}
});
});
</script>
}

Jade returning error with Unexpected token {

I keep getting an error around line 18-19 (in this case the dayClick line) saying:
Unexpected token {
at Function (native)
at assertExpression (C:\websites\timeoffcalendar\node_modules\jade\lib\lexer.js:30:33)
at Object.Lexer.conditional (C:\websites\timeoffcalendar\node_modules\jade\lib\lexer.js:509:11)
at Object.Lexer.next (C:\websites\timeoffcalendar\node_modules\jade\lib\lexer.js:914:15)
at Object.Lexer.lookahead (C:\websites\timeoffcalendar\node_modules\jade\lib\lexer.js:113:46)
at Parser.lookahead (C:\websites\timeoffcalendar\node_modules\jade\lib\parser.js:102:23)
at Parser.peek (C:\websites\timeoffcalendar\node_modules\jade\lib\parser.js:79:17)
at Parser.block (C:\websites\timeoffcalendar\node_modules\jade\lib\parser.js:704:30)
at Parser.tag (C:\websites\timeoffcalendar\node_modules\jade\lib\parser.js:817:24)
at Parser.parseTag (C:\websites\timeoffcalendar\node_modules\jade\lib\parser.js:738:17)
at Parser.parseExpr (C:\websites\timeoffcalendar\node_modules\jade\lib\parser.js:211:21)
at Parser.block (C:\websites\timeoffcalendar\node_modules\jade\lib\parser.js:708:25)
at Parser.tag (C:\websites\timeoffcalendar\node_modules\jade\lib\parser.js:817:24)
at Parser.parseTag (C:\websites\timeoffcalendar\node_modules\jade\lib\parser.js:738:17)
at Parser.parseExpr (C:\websites\timeoffcalendar\node_modules\jade\lib\parser.js:211:21)
at Parser.block (C:\websites\timeoffcalendar\node_modules\jade\lib\parser.js:708:25)
block content
script.
$(document).ready(function() {
// page is now ready, initialize the calendar...
$('#calendar').fullCalendar({
eventSources: [
{url: '/getevents'},
{url: "/javascripts/Holidays.json"},
],
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
dayClick: function(date, jsEvent, view) {
$('#calendar').fullCalendar('changeView', 'agendaDay');
$('#calendar').fullCalendar('gotoDate', date);
},
eventClick: function(event, jsEvent, view) {
$('#editModalTitle').html(event.title);
if(Cookies.get("fullAdmin") != "undefined"){
var sdate = event.start.format().split("T")[0];
var stime = event.start.format().split("T")[1];
var edate = event.end.format().split("T")[0];
var etime = event.end.format().split("T")[1];
$("#startday").val(sdate);
$("#starttime").val(stime);
$("#endday").val(edate);
$("#endtime").val(etime);
} else {
$('#startDate').html("Start date: "+event.start.format());
$('#endDate').html(" End Date: "+event.end.format());
}
$('#dayoffid').val(event.id);
$('#fullCalModal').modal();
return false;
}
});
if(Cookies.get("date") != "undefined"){
$('#calendar').fullCalendar('gotoDate', Cookies.get("date"));
Cookies.remove("date");
}
$('#allday').change(function() {
if(document.getElementById('allday').checked == true) {
$('#starttime').val("09:00:00");
$('#endtime').val("17:00:00");
}
});
$('#startday').change(function () {
$('#endday').val($('#startday').val());
});
$('#saveevent').click(function(){
$.ajax({
type: "POST",
url: "/calendar/"+$('#startday').val()+"/"+$('#starttime').val()+"/"+$('#endday').val()+"/"+$('#endtime').val()+"/"+$('#typeoptions').val()+"/"+$('#useroptions').val()
}).success(function(msg){
window.location.reload();
});
});
$('#updateEvent').click(function(){
$.ajax({
type: "PUT",
url: "/calendar/"+$('#startday').val()+"/"+$('#starttime').val()+"/"+$('#endday').val()+"/"+$('#endtime').val()+"/"+$('#typeoptions').val()+"/"+$('#useroptions').val()
}).success(function(msg){
window.location.reload();
});
});
$('#addEvent').click(function(){
$('#createModalTitle').html("Book a day off!");
$('#inputCalModal').modal();
return false;
});
$('#removeEvent').click(function() {
if(confirm("Are you sure you want to delete the event?")) {
$.ajax({
type: "DELETE",
url: "/calendar/"+$('#dayoffid').val()
}).success(function(msg){
window.location.reload();
});
}
});
});
I don't think there is a problem with your jade template, i tried it out on this site with this code..
doctype html
html(lang="en")
head
title= pageTitle
body
block content
script.
$(document).ready(function() {
// page is now ready, initialize the calendar...
//And the rest of your script
});
and it produced valid html with no errors

How to upload image in jQuery jTable

I successfully created an upload field in create mode in jQuery jTable as follows:
upload: {
title: 'Upload Image',
input: function (data) {
return '<input type="file" name="file">';
'<input type="submit" value="Submit" id="submitBtn" />';
},
},
I am able to successfully display the browse button and select files. I am unable to submit the form:
Error: newcourse.php' not found or unable to stat.
with the same file name in which the code is.
I am at a dead end. Where will the file be uploaded to? In the same directory?
How to do it in jTable ? Can it be done using ajax ? If so, how to proceed? jTable documentation is very poor.
I finally found a soluton to upload files on jTable
Now with the version of jtable 2.4.0 (the most recent at the moment writing this post)
on your file.js add the following methods:
// Read a page's GET URL variables and return them as an associative array.
function getVars(url)
{
var formData = new FormData();
var split;
$.each(url.split("&"), function(key, value) {
split = value.split("=");
formData.append(split[0], decodeURIComponent(split[1].replace(/\+/g, " ")));
});
return formData;
}
// Variable to store your files
var files;
$( document ).delegate('#input-image','change', prepareUpload);
// Grab the files and set them to our variable
function prepareUpload(event)
{
files = event.target.files;
}
//The actions for your table:
$('#table-container').jtable({
actions: {
listAction: 'backoffice/catalogs/display',
deleteAction: 'backoffice/catalogs/delete',
createAction: function (postData) {
var formData = getVars(postData);
if($('#input-image').val() !== ""){
formData.append("userfile", $('#input-image').get(0).files[0]);
}
return $.Deferred(function ($dfd) {
$.ajax({
url: 'backoffice/catalogs/update',
type: 'POST',
dataType: 'json',
data: formData,
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function (data) {
$dfd.resolve(data);
$('#table-container').jtable('load');
},
error: function () {
$dfd.reject();
}
});
});
},
updateAction: function (postData) {
var formData = getVars(postData);
if($('#input-image').val() !== ""){
formData.append("userfile", $('#input-image').get(0).files[0]);
}
return $.Deferred(function ($dfd) {
$.ajax({
url: 'backoffice/catalogs/update',
type: 'POST',
dataType: 'json',
data: formData,
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function (data) {
$dfd.resolve(data);
$('#table-container').jtable('load');
},
error: function () {
$dfd.reject();
}
});
});
},
// Now for the fields:
fields: {
id_catalog: {
key: true,
create: false,
edit: false,
list: false
},
thumb_url: {
title: 'Image',
type: 'file',
create: false,
edit: true,
list: true,
display: function(data){
return '<img src="' + data.record.thumb_url + '" width="150" height="207" class="preview">';
},
input: function(data){
return '<img src="' + data.record.thumb_url + '" width="150" height="207" class="preview">';
},
width: "150",
listClass: "class-row-center"
},
image: {
title: 'Select File',
list: false,
create: true,
input: function(data) {
html = '<input type ="file" id="input-image" name="userfile" accept="image/*" />';
return html;
}
}
}
});
Now, you are able to process the files on your server side.
That's all folks.
Hello shels
I lost a lot of time to searching of a solution of this issue. I read a many articles and found that this solution working for me fine:
actions: {
 listAction: 'modules_data.php?action=list',
deleteAction: 'modules_data.php?action=delete',
updateAction: 'modules_data.php?action=update',
createAction: 'modules_data.php?action=create'
},
...
image_file: {
title: 'Album cover',
list: true,
create: true,
edit: true,
input: function(data) {
return '<form target="iframeTarget" class="formUploadFile" action="file_upload.php" method="post" enctype="multipart/form-data"> <input type="file" onchange="this.form.submit()" name="myFile"/> </form> <iframe class="upload-iframe" style="display: none;" src="#" name="iframeTarget"></iframe>';
}
},
image: {
title: 'Album cover',
list: true,
create: true,
edit: true,
input: function(data) {
html = '<input type ="hidden" id="image" name="image" />';
return html;
}
},
....
How to capture submit response in a form created dynamically?
So you can capture submit event using:
...
formSubmitting: function(event, data) {
filename = $('input[type=file]').val().split('\\').pop();
($("#" + data.form.attr("id")).find('input[name="image"]').val(filename));
},
And save data to the server side script.
I think, it's a good solution and hope will be helpful.
Best Regards
Kameliya
console.log not working for FormData. Use instead
for (var data of formData) {
console.log(data);
}

Footer's contents don't seem to work

I'm trying create custom footers such in phantomjs examples: https://github.com/ariya/phantomjs/blob/master/examples/printheaderfooter.js
Here is my code:
var phantom = require('node-phantom');
phantom.create(function (err, ph) {
ph.createPage(function (err, page) {
page.set('paperSize', {
format: 'A4',
orientation: 'portrait',
footer: {
contents: ph.callback(function (pageNum, numPages) {
if (pageNum == 1) {
return "";
}
return "<h1>Header <span style='float:right'>" + pageNum + " / " + numPages + "</span></h1>";
})
}
}, function () {
page.open('http://www.google.com', function () {
})
})
})
});
But unfortunately I get the following error:
TypeError: Object #<Object> has no method 'callback';
Is it bug that ph does not expose callback method?
There are two problems in your script :
ph is not the classic phantom object, but a proxy object. node-phantom use web sockets to invoke phantomjs. Of course, some features are lost using this implementation.
functions are not serialized when calling page.set
Printing custom header/footer also requires to call phantom.callback. This method is not documented and so not exposed by node-phantom (and can't be). We need to find a way to apply this method in this package.
There are many solutions. Here is my possible solution :
Serialize your functions in a string in your script
var phantom = require('node-phantom');
phantom.create(function (err, ph) {
ph.createPage(function (err, page) {
page.set('paperSize', {
format: 'A4',
orientation: 'portrait',
header: {
height: "1cm",
contents: 'function(pageNum, numPages) { return pageNum + "/" + numPages; }'
},
footer: {
height: "1cm",
contents: 'function(pageNum, numPages) { return pageNum + "/" + numPages; }'
}
}, function () {
page.open('http://www.google.fr', function () {
page.render('google.pdf');
ph.exit();
})
})
})
});
edit bridge.js and add phantom.callback + eval. This allow us to re-plug the header/footer .contents.
case 'pageSet':
eval('request[4].header.contents = phantom.callback('+request[4].header.contents+')');
eval('request[4].footer.contents = phantom.callback('+request[4].footer.contents+')');
page[request[3]]=request[4];
respond([id,cmdId,'pageSetDone']);
break;
As you can see this works ! (Google in French)
Unfortunately, node-phantom doesn't appear to support phantom.callback. Since the project is inactive for more than a year, I think it's unlikely to be updated in the near future.
On the other hand, phantomjs-node supports phantom.callback() since version 0.6.6. You can use it like this:
var phantom = require('phantom');
phantom.create(function (ph) {
ph.createPage(function (page) {
page.open("http://www.google.com", function (status) {
var paperConfig = {
format: 'A4',
orientation: 'portrait',
border: '1cm',
header: {
height: '1cm',
contents: ph.callback(function(pageNum, numPages) {
return '<h1>My Custom Header</h1>';
})
},
footer: {
height: '1cm',
contents: ph.callback(function(pageNum, numPages) {
return '<p>Page ' + pageNum + ' / ' + numPages + '</p>';
})
}
};
page.set('paperSize', paperConfig, function() {
// render to pdf
page.render('path/to/file.pdf', function() {
page.close();
ph.exit();
});
});
});
});
});
As you can also see on this gist.
node phantom seems to expose this proxy-object via the create function (this should be your ph-object):
var proxy={
createPage:function(callback){
request(socket,[0,'createPage'],callbackOrDummy(callback));
},
injectJs:function(filename,callback){
request(socket,[0,'injectJs',filename],callbackOrDummy(callback));
},
addCookie: function(cookie, callback){
request(socket,[0,'addCookie', cookie],callbackOrDummy(callback));
},
exit:function(callback){
request(socket,[0,'exit'],callbackOrDummy(callback));
},
on: function(){
phantom.on.apply(phantom, arguments);
},
_phantom: phantom
};
that means, that you can probably acces the phantoms callback like this:
ph._phantom.callback
Here what I did to access phantom.callback:
add this to node-phantom.js line 202:
callback: function(callback){
request(socket,[0,'callback'],callbackOrDummy(callback));
},
just before _phantom: phantom
and add this to bridge.js line 45:
case 'callback':
phantom.callback(request[3]);
break;
Hope it helps!

Resources