Jquery Custom Parser Not working - javascript

I have a table which have input field in the 2 nd column (1st if started with index 0). It works fine and sort all regular columns except the column which have textboxes. Here's what I've,
Javascript Code
<script src="jQuery-2.1.4.min.js"></script>
<script type="text/javascript" src="jquery.tablesorter.min.js"></script>
<script>
$('#ordertbldata').tablesorter({
headers: {
1: {
sorter: 'textbox_text'
}
}
});
$.tablesorter.addParser({
id: 'textbox_text',
is: function(s) {
console.log('function is called');
return false;
},
format: function(s) {
console.log('function format called');
return $($.trim(s)).val();
},
type: "text"
});
</script>
I've added log function to debug but the function isn't called. What's wrong I'm doing here ?
UPDATE : Fiddle here

Your demo was declaring the parser after initializing the plugin.
Seems to work well with this configuration
$.tablesorter.addParser({
id: 'textbox_text',
is: function(s) {
return false;
},
format: function(s,table, el) {
return $.trim($(el).find('input').val().toLowerCase());
},
type: "text",
parsed: true,
});
DEMO

Related

Jquery Autocomplete submit form on select - Why this code dont work?

I am newby on javascript/Jquery. Can someome tell me how write this code correctly?
The part of the code wont work is:
select: function (event) {
$("#busca-site").val(item.title);
$("#form-busca-site").submit();
}
Complete code:
$('#busca-site').autocomplete({
valueKey:'title',
accents:true,
replaceAccentsForRemote: true,
source:[{
url:"https://www.example.com/teste2/teste_search2.asp?q=%QUERY% ",
type:'remote',
getValueFromItem:function(item){
return item.title
},
ajax:{
dataType : 'json'
}
}],
select: function (event) {
$("#busca-site").val(item.title);
$("#form-busca-site").submit();
}
});
UPDATE 1 - The original main code fully functional is:
$('#busca-site').autocomplete({
valueKey:'title',
accents:true,
replaceAccentsForRemote: true,
source:[{
url:"https://www.example.com/teste2/teste_search2.asp?q=%QUERY% ",
type:'remote',
getValueFromItem:function(item){
return item.title
},
ajax:{
dataType : 'json'
}
}]
});
Following the #Swati tip that he observed the plugin has a built in function, the working code would be:
$('#busca-site').autocomplete({
valueKey:'title',
accents:true,
replaceAccentsForRemote: true,
source:[{
url:"https://www.example.com/teste2/teste_search2.asp?q=%QUERY% ",
type:'remote',
getValueFromItem:function(item){
return item.title
},
ajax:{
dataType : 'json'
},
}]
}).on('selected.xdsoft',function(e,datum){
//alert(datum.id);
$("#form-busca-site").submit();
//alert(datum.title);
});

Merging two json file and using it in autocoplete plugin

I am trying to merge two JSON file and using it in autocompleteplugin.
But I do get an error TypeError: $(...).easyAutocomplete is not a function even I have added js library for both auto complete and jquery.
My code look like this:
<script src="jquery-3.1.0.js"></script>
<link href="easy-autocomplete.min.css" rel="stylesheet" />
<script src="jquery.easy-autocomplete.min.js"></script>
<script>
$.getJSON("file1.json", function (data1) {
$.getJSON("file2.json", function (data2) {
var final = $.extend({}, data1, data2);
var options = {
data: final,
getValue: "name",
list: {
match: {
enabled: true
}
},
theme: "square"
};
$("#KUNDE").easyAutocomplete(options); $('div.easy-autocomplete').removeAttr('style');
});
});
</script>
I made a working example based on your code.
Please check you have the correct paths when you include the script files. And also check if jQuery is included.
Hope will help you:
$.getJSON("https://api.myjson.com/bins/42jd0", function (data1) {
$.getJSON("https://api.myjson.com/bins/5bjqc", function (data2) {
var final = [];
final.push(data1.employees1);
final.push(data2.employees2);
var new_final = final[0].concat(final[1]);
var options = {
data: new_final,
getValue: "firstName",
list: {
match: {
enabled: true
}
},
theme: "square"
};
$("#KUNDE").easyAutocomplete(options); $('div.easy-autocomplete').removeAttr('style');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/easy-autocomplete/1.3.5/easy-autocomplete.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/easy-autocomplete/1.3.5/jquery.easy-autocomplete.min.js"></script>
<div class='easy-autocomplete'>
<input id="KUNDE"/>
</div>
You can run the code here by hitting the Run code snippet button or you can also check the jsfiddle I've made here.

Tablesorters addparse gives "undefined is not a function "

Tablesorter isn't acception .addParser somehow. I get the error "undefined is not a function".
This is my code:
$('mytable').tablesorter({
sortList: [[0,0]],
sortRestart: true,
initialized: function(table) {
var currentTable = $(table);
var startcol = currentTable.data("startcol");
if (startcol) {
var sorting = [[startcol, 0]];
currentTable.trigger("sorton", [sorting]);
}
},
headers:
{
4: { sorter: 'customparse' },
5: { sorter: 'customparse' }
}
}).addParser({
id: 'customparse',
is: function (s) {
return false;
},
format: function (s) {
console.log(s);
return s.replace(/\s+/g, '').replace(/,/g, '.');
},
type: 'numeric'
});
I found some other related questions and cant find my issue.. I've doubble check that jQuery isnt included twice. It works fine without addPareser even thought the jQuery version Im using is 1.11. But I tried updating to version 2.1 but no change..
Am I initiating it wrong? what am I doing wrong..
To add a parser, you need to use $.tablesorter.addParser(). You cannot access the method from a jQuery object, as you're trying to do.
Because you are adding the parser wrong
$.tablesorter.addParser({ ... });
Documentation Example
$.tablesorter.addParser({
id: 'customparse',
is: function (s) {
return false;
},
format: function (s) {
console.log(s);
return s.replace(/\s+/g, '').replace(/,/g, '.');
},
type: 'numeric'
});
Do the above before you instantiate the tablesorter on your table.

Select2 limit number of tags

Is there a way to limit the number of tags a user can add to an input field using Select2?
I have:
$('#tags').select2({
containerCssClass: 'supplierTags',
placeholder: "Usual suppliers...",
minimumInputLength: 2,
multiple: true,
tokenSeparators: [",", " "],
placeholder: 'Usual suppliers...',
createSearchChoice: function(term, data) {
if ($(data).filter(function() {
return this.name.localeCompare(term) === 0;
}).length === 0) {
return {id: 0, name: term};
}
},
id: function(e) {
return e.id + ":" + e.name;
},
ajax: {
url: ROOT + 'Call',
dataType: 'json',
type: 'POST',
data: function(term, page) {
return {
call: 'Helpers->tagsHelper',
q: term
};
},
results: function(data, page) {
return {
results: data.tags
};
}
},
formatResult: formatResult,
formatSelection: formatSelection,
initSelection: function(element, callback) {
var data = [];
$(element.val().split(",")).each(function(i) {
var item = this.split(':');
data.push({
id: item[0],
name: item[1]
});
});
callback(data);
}
});
It would be great if there could be/is a simple parameter like limit: 5 and a callback to fire when the limit is reached.
Sure, with maximumSelectionLength like so:
$("#tags").select2({
maximumSelectionLength: 3
});
Maximum Selection Length
Select2 allows the developer to limit the number of items that can be
selected in a multi-select control.
http://ivaynberg.github.io/select2/
It has no native callback, but you can pass a function to formatSelectionTooBig like this:
$(function () {
$("#tags").select2({
maximumSelectionLength: 3,
formatSelectionTooBig: function (limit) {
// Callback
return 'Too many selected items';
}
});
});
http://jsfiddle.net/U98V7/
Or you could extend formatSelectionTooBig like this:
$(function () {
$.extend($.fn.select2.defaults, {
formatSelectionTooBig: function (limit) {
// Callback
return 'Too many selected items';
}
});
$("#tags").select2({
maximumSelectionLength: 3
});
});
Edit
Replaced maximumSelectionSize with the updated maximumSelectionLength. Thanks #DrewKennedy!
method 1
$("#tags").select2({
maximumSelectionLength: 3
});
method 2
<select data-maximum-selection-length="3" ></select>
list of all available options https://select2.org/configuration/options-api
The accepted answer doesn't mention that the maximumSelectionLength statement should be inside the document.ready function. So for anyone who is having the same trouble I did, here is the code that worked for me.
$(document).ready(function() {
$("#id").select2({
maximumSelectionLength: 3
});
});
$("#keywords").select2({
tags : true,
width :'100%',
tokenSeparators: [','],
maximumSelectionLength: 5,
matcher : function(term,res){
return false;
},
"language": {
'noResults': function(){
return "Type keywords separated by commas";
}
}
}).on("change",function(e){
if($(this).val().length>5){
$(this).val($(this).val().slice(0,5));
}
});
Try like this. It'll short up to 5 keywords.
This is not working for me, I am getting query function not defined for Select2, so here is another workaround.
var onlyOne=false;
$("selector").select2({
maximumSelectionSize:function(){
if(onlyOne==true)
return 1;
else
return 5;
}
});
This setting can be defined as function and it's called every time you start searching something.
Important thing is that you have something defined outside this select2 closure so you can check it (access it). In this case you could somewhere in your program change value of onlyOne and of course this returned limit can also be dynamical.
This is working for me.
$("#category_ids").select2({ maximumSelectionLength: 3 });
Send the Get Request to action method and the Map the class properties to drop down id and text property
$("#DropDownId").select2({
minimumInputLength: 3,
maximumSelectionLength: 10,
tags: [],
ajax: {
url: "#Url.Action("ActionName", "ControllerName")",
type: "get",
dataType: 'json',
delay: 250,
data: function (params) {
return {
Title: params.term // search term
};
},
processResults: function (response) {
return {
results: $.map(response, function (item) {
return {
text: item.Title,
id: item.Id
}
})
};
}
}
});
Action Method
[HttpGet]
public JsonResult ActionName(string Title)
{
ClassName obj= new ClassName ();
obj.Title = "PMPAK";
obj.Id= -1;
obj.Add(nibafInstitute);
return Json(obj, JsonRequestBehavior.AllowGet);
}
public class ClassName
{
public int Id{ get; set; }
public string Title { get; set; }
}

jQuery ui autocomplete usin JSON file

I am having some trouble getting autocomplete to work specifically with a json file. It
giving following error whenever something is entered in the text box
url is undefined
following is my jQuery code
$(document).ready(function() {
$('#autocomplete').autocomplete({
minChars: 1,
source: function(request, response) {
var url='dataa.json';
$.getJSON(url,{term: request.term},function(data){
response($.map(data.ledgers, function(item) {
return item.value;
}));
})
}
});
});
and the JSON
{
"ledgers":
[
{
"id":"2001",
"name":"Bharat"
},
{
"id":"2003",
"name":"Gaurav"
},
{
"id":"2002",
"name":"Pankaj"
},
{
"id":"2022",
"name":"Purchase"
},
{
"id":"2007",
"name":"Ram"
},
{
"id":"2008",
"name":"Ramesh"
},
{
"id":"2009",
"name":"Suresh"
}
]}
Your JSON file format needs to contain value or label (or both). Change name to value and it should work fine.
$('#autocomplete').autocomplete({
minChars: 1,
source: function(request, response) {
var url='dataa.json';
$.getJSON(url,{term: request.term},function(data){
response($.map(data.ledgers, function (value, key) {
return {
label: value,
value: key
};
}));
})
}
});
Try adding 'use strict'; at the top of your $(document).ready(). That may point out what the problem is...
return item.value;
item does not have a value, try returning id or name, which it does have.

Categories

Resources