Select2 in v3.x and v4.x - javascript

The code below works with select2 Version: 3.X but when I use "https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.full.min.js" and "https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" it does not add the values:
var data = [];
for(var i = 0; i < 10000; i++){
data.push({id: ""+i, text: ""+i});
}
$("input").select2({
initSelection: function(element, callback) {
var selection = _.find(data, function(metric){
return metric.id === element.val();
})
callback(selection);
},
query: function(options){
var pageSize = 100;
var startIndex = (options.page - 1) * pageSize;
var filteredData = data;
if( options.term && options.term.length > 0 ){
if( !options.context ){
var term = options.term.toLowerCase();
options.context = data.filter( function(metric){
return ( metric.text.toLowerCase().indexOf(term) !== -1 );
});
}
filteredData = options.context;
}
options.callback({
context: filteredData,
results: filteredData.slice(startIndex, startIndex + pageSize),
more: (startIndex + pageSize) < filteredData.length
});
},
placeholder: "Select a metric"
});
here is the link of jsfiddle:
http://jsfiddle.net/Z7bDG/1/

Related

Reviews Not Being Fetched

My google reviews are not being fetched. I've tried the code below but it doesn't work. I've created an api and put this in along with my placeid in all of the code below but nothing displays.
I followed multiple tutorials which all give basically the same code. I'm not sure why this isn't working.
Does anyone know what I'm doing wrong or have any suggestions on how to implement this in an easier way.
html:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="/js/google-places.js "></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places&key=[API_KEY]"></script>
<script>
jQuery(document).ready(function() {
$("#google-reviews").googlePlaces({
placeId: '[PLACES_ID]',
render: ['reviews'],
min_rating: 3,
max_rows: 0
});
});
</script>
</head>
<body>
<div id="google-reviews"></div>
</body>
javascript:
/* https://github.com/peledies/google-places */
(function($) {
var namespace = 'googlePlaces';
$.googlePlaces = function(element, options) {
var defaults = {
placeId: 'PLACEID' // placeId provided by google api documentation
, render: ['reviews']
, min_rating: 3
, max_rows: 0
, map_plug_id: 'map-plug'
, rotateTime: false
, shorten_names: true
, schema:{
displayElement: '#schema'
, type: 'Store'
, beforeText: 'Google Users Have Rated'
, middleText: 'based on'
, afterText: 'ratings and reviews'
, image: null
, priceRange: null
}
, address:{
displayElement: "#google-address"
}
, phone:{
displayElement: "#google-phone"
}
, staticMap:{
displayElement: "#google-static-map"
, width: 512
, height: 512
, zoom: 17
, type: "roadmap"
}
, hours:{
displayElement: "#google-hours"
}
};
var plugin = this;
plugin.settings = {}
var $element = $(element),
element = element;
plugin.init = function() {
plugin.settings = $.extend({}, defaults, options);
plugin.settings.schema = $.extend({}, defaults.schema, options.schema);
$element.html("<div id='" + plugin.settings.map_plug_id + "'></div>"); // create a plug for google to load data into
initialize_place(function(place){
plugin.place_data = place;
// Trigger event before render
$element.trigger('beforeRender.' + namespace);
if(plugin.settings.render.indexOf('rating') > -1){
renderRating(plugin.place_data.rating);
}
// render specified sections
if(plugin.settings.render.indexOf('reviews') > -1){
renderReviews(plugin.place_data.reviews);
if(!!plugin.settings.rotateTime) {
initRotation();
}
}
if(plugin.settings.render.indexOf('address') > -1){
renderAddress(
capture_element(plugin.settings.address.displayElement)
, plugin.place_data.adr_address
);
}
if(plugin.settings.render.indexOf('phone') > -1){
renderPhone(
capture_element(plugin.settings.phone.displayElement)
, plugin.place_data.formatted_phone_number
);
}
if(plugin.settings.render.indexOf('staticMap') > -1){
renderStaticMap(
capture_element(plugin.settings.staticMap.displayElement)
, plugin.place_data.formatted_address
);
}
if(plugin.settings.render.indexOf('hours') > -1){
renderHours(
capture_element(plugin.settings.hours.displayElement)
, plugin.place_data.opening_hours
);
}
// render schema markup
addSchemaMarkup(
capture_element(plugin.settings.schema.displayElement)
, plugin.place_data
);
// Trigger event after render
$element.trigger('afterRender.' + namespace);
});
}
var capture_element = function(element){
if(element instanceof jQuery){
return element;
}else if(typeof element == 'string'){
try{
var ele = $(element);
if( ele.length ){
return ele;
}else{
throw 'Element [' + element + '] couldnt be found in the DOM. Skipping '+element+' markup generation.';
}
}catch(e){
console.warn(e);
}
}
}
var initialize_place = function(c){
var map = new google.maps.Map(document.getElementById(plugin.settings.map_plug_id));
var request = {
placeId: plugin.settings.placeId
};
var service = new google.maps.places.PlacesService(map);
service.getDetails(request, function(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
c(place);
}
});
}
var sort_by_date = function(ray) {
ray.sort(function(a, b){
var keyA = new Date(a.time),
keyB = new Date(b.time);
// Compare the 2 dates
if(keyA < keyB) return -1;
if(keyA > keyB) return 1;
return 0;
});
return ray;
}
var filter_minimum_rating = function(reviews){
for (var i = reviews.length -1; i >= 0; i--) {
if(reviews[i].rating < plugin.settings.min_rating){
reviews.splice(i,1);
}
}
return reviews;
}
var renderRating = function(rating){
var html = "";
var star = renderAverageStars(rating);
html = "<div class='average-rating'><h4>"+star+"</h4></div>";
$element.append(html);
}
var shorten_name = function(name) {
if (name.split(" ").length > 1) {
var xname = "";
xname = name.split(" ");
return xname[0] + " " + xname[1][0] + ".";
}
}
var renderReviews = function(reviews){
reviews = sort_by_date(reviews);
reviews = filter_minimum_rating(reviews);
var html = "";
var row_count = (plugin.settings.max_rows > 0)? plugin.settings.max_rows - 1 : reviews.length - 1;
// make sure the row_count is not greater than available records
row_count = (row_count > reviews.length-1)? reviews.length -1 : row_count;
for (var i = row_count; i >= 0; i--) {
var stars = renderStars(reviews[i].rating);
var date = convertTime(reviews[i].time);
if(plugin.settings.shorten_names == true) {
var name = shorten_name(reviews[i].author_name);
} else {
var name = reviews[i].author_name + "</span><span class='review-sep'>, </span>";
};
html = html+"<div class='review-item'><div class='review-meta'><span class='review-author'>"+name+"<span class='review-date'>"+date+"</span></div>"+stars+"<p class='review-text'>"+reviews[i].text+"</p></div>"
};
$element.append(html);
}
var renderHours = function(element, data){
if(element instanceof jQuery){
var html = "<ul>";
data.weekday_text.forEach(function(day){
html += "<li>"+day+"</li>";
});
html += "</ul>";
element.append(html);
}
}
var renderStaticMap = function(element, data){
if(element instanceof jQuery){
var map = plugin.settings.staticMap;
element.append(
"<img src='https://maps.googleapis.com/maps/api/staticmap"+
"?size="+map.width+"x"+map.height+
"&zoom="+map.zoom+
"&maptype="+map.type+
"&markers=size:large%7Ccolor:red%7C"+data+"'>"+
"</img>");
}
}
var renderAddress = function(element, data){
if(element instanceof jQuery){
element.append(data);
}
}
var renderPhone = function(element, data){
if(element instanceof jQuery){
element.append(data);
}
}
var initRotation = function() {
var $reviewEls = $element.children('.review-item');
var currentIdx = $reviewEls.length > 0 ? 0 : false;
$reviewEls.hide();
if(currentIdx !== false) {
$($reviewEls[currentIdx]).show();
setInterval(function(){
if(++currentIdx >= $reviewEls.length) {
currentIdx = 0;
}
$reviewEls.hide();
$($reviewEls[currentIdx]).fadeIn('slow');
}, plugin.settings.rotateTime);
}
}
var renderStars = function(rating){
var stars = "<div class='review-stars'><ul>";
// fill in gold stars
for (var i = 0; i < rating; i++) {
stars = stars+"<li><i class='star'></i></li>";
};
// fill in empty stars
if(rating < 5){
for (var i = 0; i < (5 - rating); i++) {
stars = stars+"<li><i class='star inactive'></i></li>";
};
}
stars = stars+"</ul></div>";
return stars;
}
var renderAverageStars = function(rating){
var stars = "<div class='review-stars'><ul><li><i>"+rating+" </i></li>";
var activeStars = parseInt(rating);
var inactiveStars = 5 - activeStars;
var width = (rating - activeStars) * 100 + '%';
// fill in gold stars
for (var i = 0; i < activeStars; i++) {
stars += "<li><i class='star'></i></li>";
};
// fill in empty stars
if(inactiveStars > 0){
for (var i = 0; i < inactiveStars; i++) {
if (i === 0) {
stars += "<li style='position: relative;'><i class='star inactive'></i><i class='star' style='position: absolute;top: 0;left: 0;overflow: hidden;width: "+width+"'></i></li>";
} else {
stars += "<li><i class='star inactive'></i></li>";
}
};
}
stars += "</ul></div>";
return stars;
}
var convertTime = function(UNIX_timestamp){
var a = new Date(UNIX_timestamp * 1000);
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var time = months[a.getMonth()] + ' ' + a.getDate() + ', ' + a.getFullYear();
return time;
}
var addSchemaMarkup = function(element, placeData) {
if(element instanceof jQuery){
var schema = plugin.settings.schema;
var schemaMarkup = '<span itemscope="" itemtype="http://schema.org/' + schema.type + '">';
if(schema.image !== null) {
schemaMarkup += generateSchemaItemMarkup('image', schema.image);
} else {
console.warn('Image is required for some schema types. Visit https://search.google.com/structured-data/testing-tool to test your schema output.');
}
if(schema.priceRange !== null) {
schemaMarkup += generateSchemaItemMarkup('priceRange', schema.priceRange);
}
schemaMarkup += generateSchemaItemMarkup('url', location.origin);
schemaMarkup += generateSchemaItemMarkup('telephone', plugin.place_data.formatted_phone_number );
schemaMarkup += generateSchemaAddressMarkup();
schemaMarkup += generateSchemaRatingMarkup(placeData, schema);
schemaMarkup += '</span>';
element.append(schemaMarkup);
}
}
var generateSchemaAddressMarkup = function() {
var $address = $('<div />', {
itemprop: "address"
, itemscope: ''
, itemtype: "http://schema.org/PostalAddress"
}).css('display', 'none');
$address.append(plugin.place_data.adr_address);
$address.children('.street-address').attr('itemprop', 'streetAddress');
$address.children('.locality').attr('itemprop', 'addressLocality');
$address.children('.region').attr('itemprop', 'addressRegion');
$address.children('.postal-code').attr('itemprop', 'postalCode');
$address.children('.country-name').attr('itemprop', 'addressCountry');
return $address[0].outerHTML;
}
var generateSchemaRatingMarkup = function(placeData, schema) {
var reviews = placeData.reviews;
var lastIndex = reviews.length - 1;
var reviewPointTotal = 0;
for (var i = lastIndex; i >= 0; i--) {
reviewPointTotal += reviews[i].rating;
};
var averageReview = reviewPointTotal / ( reviews.length );
return schema.beforeText + ' <span itemprop="name">' + placeData.name + '</span> '
+ '<span itemprop="aggregateRating" itemscope="" itemtype="http://schema.org/AggregateRating">'
+ '<span itemprop="ratingValue">' + averageReview.toFixed(2) + '</span>/<span itemprop="bestRating">5</span> '
+ schema.middleText + ' <span itemprop="ratingCount">' + reviews.length + '</span> '
+ schema.afterText
+ '</span>'
}
var generateSchemaItemMarkup = function(name, value) {
return '<meta itemprop="' + name + '" content="' + value + '">'
}
plugin.init();
}
$.fn.googlePlaces = function(options) {
return this.each(function() {
if (undefined == $(this).data(namespace)) {
var plugin = new $.googlePlaces(this, options);
$(this).data(namespace, plugin);
}
});
}
})(jQuery);
I've also tried just this instead of everything above but still nothing displays.
html:
<div id="google-reviews"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://tutorialswebsite.com/cdn/google_places.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=APIKEY&signed_in=true&libraries=places"></script>
<script>
jQuery(document).ready(function( $ ) {
$("#google-reviews").googlePlaces({
placeId: 'PLACEID' //Find placeID #: https://developers.google.com/places/place-id
, render: ['reviews']
, min_rating:3
, max_rows:5
,rotateTime: false
, shorten_names: true
});
});
</script>

Using Javascript to do comparison of user inputs

I have the following code that is using 3 columns to check for difference in input values.
The third column difference in my view is generated fine but while viewing it the table is not displaying it.
What is want to do is to compare base text with new text and thrid text input enteries and display the changes to user in inline or side by side format
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
<title>jsdifflib demo</title>
<link rel="stylesheet" type="text/css" href="diffview.css"/>
<script type="text/javascript" src="diffview.js"></script>
<script type="text/javascript" src="difflib.js"></script>
<style type="text/css">
body {
font-size: 12px;
font-family: Sans-Serif,serif;
}
h2 {
margin: 0.5em 0 0.1em;
text-align: center;
}
.top {
text-align: center;
}
.textInput {
display: block;
width: 49%;
float: left;
}
textarea {
width:100%;
height:300px;
}
label:hover {
text-decoration: underline;
cursor: pointer;
}
.spacer {
margin-left: 10px;
}
.viewType {
font-size: 16px;
clear: both;
text-align: center;
padding: 1em;
}
#diffoutput {
width: 100%;
}
</style>
<script type="text/javascript">
function diffUsingJS(viewType) {
"use strict";
var byId = function (id) { return document.getElementById(id); },
base = difflib.stringAsLines(byId("baseText").value),
newtxt = difflib.stringAsLines(byId("newText").value),
thirdText = difflib.stringAsLines(byId("3rdText").value),
sm = new difflib.SequenceMatcher(base, newtxt, thirdText),
opcodes = sm.get_opcodes(),
diffoutputdiv = byId("diffoutput"),
contextSize = byId("contextSize").value;
diffoutputdiv.innerHTML = "";
contextSize = contextSize || null;
diffoutputdiv.appendChild(diffview.buildView({
baseTextLines: base,
newTextLines: newtxt,
thirdTextLines: thirdText,
opcodes: opcodes,
baseTextName: "Base Text",
newTextName: "New Text",
thirdTextName: "Third Text",
contextSize: contextSize,
viewType: viewType
}));
}
</script>
</head>
<body>
<div class="top">
<strong>Context size (optional):</strong> <input type="text" id="contextSize" value="" />
</div>
<div class="textInput">
<h2>Base Text</h2>
<textarea id="baseText" >a</textarea>
</div>
<div class="textInput spacer">
<h2>New Text</h2>
<textarea id="newText">b</textarea>
</div>
<div class="textInput spacer">
<h2>3rd Text</h2>
<textarea id="3rdText">c</textarea>
</div>
<div class="viewType">
<input type="radio" name="_viewtype" id="sidebyside" onclick="diffUsingJS(0);" /> <label for="sidebyside">Side by Side Diff</label>
<input type="radio" name="_viewtype" id="inline" onclick="diffUsingJS(1);" /> <label for="inline">Inline Diff</label>
</div>
<div id="diffoutput"> </div>
</body>
</html>
diffview.js
var diffview = {
/**
* Builds and returns a visual diff view. The single parameter, `params', should contain
* the following values:
*
* - baseTextLines: the array of strings that was used as the base text input to SequenceMatcher
* - newTextLines: the array of strings that was used as the new text input to SequenceMatcher
* - opcodes: the array of arrays returned by SequenceMatcher.get_opcodes()
* - baseTextName: the title to be displayed above the base text listing in the diff view; defaults
* to "Base Text"
* - newTextName: the title to be displayed above the new text listing in the diff view; defaults
* to "New Text"
* - contextSize: the number of lines of context to show around differences; by default, all lines
* are shown
* - viewType: if 0, a side-by-side diff view is generated (default); if 1, an inline diff view is
* generated
*/
buildView: function (params) {
var baseTextLines = params.baseTextLines;
var newTextLines = params.newTextLines;
var thirdTextLines = params.thirdTextLines;
var opcodes = params.opcodes;
var baseTextName = params.baseTextName ? params.baseTextName : "Base Text";
var newTextName = params.newTextName ? params.newTextName : "New Text";
var thirdTextName = params.thirdTextName ? params.thirdTextName: "Third Text"
var contextSize = params.contextSize;
var inline = (params.viewType == 0 || params.viewType == 1) ? params.viewType : 0;
if (baseTextLines == null)
throw "Cannot build diff view; baseTextLines is not defined.";
if (newTextLines == null)
throw "Cannot build diff view; newTextLines is not defined.";
if (thirdTextLines == null)
throw "Cannot build diff view; thirdTextLines is not defined.";
if (!opcodes)
throw "Canno build diff view; opcodes is not defined.";
function celt (name, clazz) {
var e = document.createElement(name);
e.className = clazz;
return e;
}
function telt (name, text) {
var e = document.createElement(name);
e.appendChild(document.createTextNode(text));
return e;
}
function ctelt (name, clazz, text) {
var e = document.createElement(name);
e.className = clazz;
e.appendChild(document.createTextNode(text));
return e;
}
var tdata = document.createElement("thead");
var node = document.createElement("tr");
tdata.appendChild(node);
if (inline) {
node.appendChild(document.createElement("th"));
node.appendChild(document.createElement("th"));
node.appendChild(ctelt("th", "texttitle", baseTextName + " vs. " + newTextName + " vs. " + thirdTextName));
} else {
node.appendChild(document.createElement("th"));
node.appendChild(ctelt("th", "texttitle", baseTextName));
node.appendChild(document.createElement("th"));
node.appendChild(ctelt("th", "texttitle", newTextName));
node.appendChild(document.createElement("th"));
node.appendChild(ctelt("th", "texttitle", thirdTextName));
}
tdata = [tdata];
var rows = [];
var node2;
/**
* Adds two cells to the given row; if the given row corresponds to a real
* line number (based on the line index tidx and the endpoint of the
* range in question tend), then the cells will contain the line number
* and the line of text from textLines at position tidx (with the class of
* the second cell set to the name of the change represented), and tidx + 1 will
* be returned. Otherwise, tidx is returned, and two empty cells are added
* to the given row.
*/
function addCells (row, tidx, tend, textLines, change) {
if (tidx < tend) {
row.appendChild(telt("th", (tidx + 1).toString()));
row.appendChild(ctelt("td", change, textLines[tidx].replace(/\t/g, "\u00a0\u00a0\u00a0\u00a0")));
return tidx + 1;
} else {
row.appendChild(document.createElement("th"));
row.appendChild(celt("td", "empty"));
return tidx;
}
}
function addCellsInline (row, tidx, tidx2, textLines, change) {
row.appendChild(telt("th", tidx == null ? "" : (tidx + 1).toString()));
row.appendChild(telt("th", tidx2 == null ? "" : (tidx2 + 1).toString()));
row.appendChild(ctelt("td", change, textLines[tidx != null ? tidx : tidx2].replace(/\t/g, "\u00a0\u00a0\u00a0\u00a0")));
}
for (var idx = 0; idx < opcodes.length; idx++) {
code = opcodes[idx];
change = code[0];
var b = code[1];
var be = code[2];
var n = code[3];
var ne = code[4];
var rowcnt = Math.max(be - b, ne - n);
var toprows = [];
var botrows = [];
for (var i = 0; i < rowcnt; i++) {
// jump ahead if we've alredy provided leading context or if this is the first range
if (contextSize && opcodes.length > 1 && ((idx > 0 && i == contextSize) || (idx == 0 && i == 0)) && change=="equal") {
var jump = rowcnt - ((idx == 0 ? 1 : 2) * contextSize);
if (jump > 1) {
toprows.push(node = document.createElement("tr"));
b += jump;
n += jump;
i += jump - 1;
node.appendChild(telt("th", "..."));
if (!inline) node.appendChild(ctelt("td", "skip", ""));
node.appendChild(telt("th", "..."));
node.appendChild(ctelt("td", "skip", ""));
// skip last lines if they're all equal
if (idx + 1 == opcodes.length) {
break;
} else {
continue;
}
}
}
toprows.push(node = document.createElement("tr"));
if (inline) {
if (change == "insert") {
addCellsInline(node, null, n++, newTextLines, change);
} else if (change == "replace") {
botrows.push(node2 = document.createElement("tr"));
if (b < be) addCellsInline(node, b++, null, baseTextLines, "delete");
if (n < ne) addCellsInline(node2, null, n++, newTextLines, "insert");
if (n < ne) addCellsInline(node2, null, n++, thirdTextLines, "insert");
} else if (change == "delete") {
addCellsInline(node, b++, null, baseTextLines, change);
} else {
// equal
addCellsInline(node, b++, n++, baseTextLines, change);
}
} else {
b = addCells(node, b, be, baseTextLines, change);
n = addCells(node, n, ne, newTextLines, change);
n = addCells(node, n, ne, thirdTextLines, change);
}
}
for (var i = 0; i < toprows.length; i++) rows.push(toprows[i]);
for (var i = 0; i < botrows.length; i++) rows.push(botrows[i]);
}
tdata.push(node = document.createElement("tbody"));
for (var idx in rows) rows.hasOwnProperty(idx) && node.appendChild(rows[idx]);
node = celt("table", "diff" + (inline ? " inlinediff" : ""));
for (var idx in tdata) tdata.hasOwnProperty(idx) && node.appendChild(tdata[idx]);
return node;
}
};
difflib.js
var __whitespace = {" ":true, "\t":true, "\n":true, "\f":true, "\r":true};
var difflib = {
defaultJunkFunction: function (c) {
return __whitespace.hasOwnProperty(c);
},
stripLinebreaks: function (str) { return str.replace(/^[\n\r]*|[\n\r]*$/g, ""); },
stringAsLines: function (str) {
var lfpos = str.indexOf("\n");
var crpos = str.indexOf("\r");
var linebreak = ((lfpos > -1 && crpos > -1) || crpos < 0) ? "\n" : "\r";
var lines = str.split(linebreak);
for (var i = 0; i < lines.length; i++) {
lines[i] = difflib.stripLinebreaks(lines[i]);
}
return lines;
},
// iteration-based reduce implementation
__reduce: function (func, list, initial) {
if (initial != null) {
var value = initial;
var idx = 0;
} else if (list) {
var value = list[0];
var idx = 1;
} else {
return null;
}
for (; idx < list.length; idx++) {
value = func(value, list[idx]);
}
return value;
},
// comparison function for sorting lists of numeric tuples
__ntuplecomp: function (a, b) {
var mlen = Math.max(a.length, b.length);
for (var i = 0; i < mlen; i++) {
if (a[i] < b[i]) return -1;
if (a[i] > b[i]) return 1;
}
return a.length == b.length ? 0 : (a.length < b.length ? -1 : 1);
},
__calculate_ratio: function (matches, length) {
return length ? 2.0 * matches / length : 1.0;
},
// returns a function that returns true if a key passed to the returned function
// is in the dict (js object) provided to this function; replaces being able to
// carry around dict.has_key in python...
__isindict: function (dict) {
return function (key) { return dict.hasOwnProperty(key); };
},
// replacement for python's dict.get function -- need easy default values
__dictget: function (dict, key, defaultValue) {
return dict.hasOwnProperty(key) ? dict[key] : defaultValue;
},
SequenceMatcher: function (a, b, c, isjunk) {
this.set_seqs = function (a, b, c, ) {
this.set_seq1(a);
this.set_seq2(b);
this.set_seq3(c);
}
this.set_seq1 = function (a) {
if (a == this.a) return;
this.a = a;
this.matching_blocks = this.opcodes = null;
}
this.set_seq2 = function (b) {
console.log("Value in set ", b)
if (b == this.b) return;
this.b = b;
this.matching_blocks = this.opcodes = this.fullbcount = null;
this.__chain_b();
}
this.set_seq3 = function (c) {
console.log("Value in set ", c)
if (c == this.c) return;
this.c = c;
this.matching_blocks = this.opcodes = this.fullbcount = null;
this.__chain_c();
}
this.__chain_c = function () {
console.log("This is ", this.c)
var c = this.c;
var n = c.length;
var c2j = this.c2j = {};
var populardict = {};
for (var i = 0; i < c.length; i++) {
var celt = c[i];
if (c2j.hasOwnProperty(celt)) {
var indices = c2j[elt];
if (n >= 200 && indices.length * 100 > n) {
populardict[celt] = 1;
delete c2j[celt];
} else {
indices.push(i);
}
} else {
c2j[celt] = [i];
}
}
for (var elt in populardict) {
if (populardict.hasOwnProperty(elt)) {
delete c2j[elt];
}
}
var isjunk = this.isjunk;
var junkdict = {};
if (isjunk) {
for (var elt in populardict) {
if (populardict.hasOwnProperty(elt) && isjunk(elt)) {
junkdict[elt] = 1;
delete populardict[elt];
}
}
for (var elt in c2j) {
if (c2j.hasOwnProperty(elt) && isjunk(elt)) {
junkdict[elt] = 1;
delete c2j[elt];
}
}
}
this.iscjunk = difflib.__isindict(junkdict);
this.iscpopular = difflib.__isindict(populardict);
}
this.__chain_b = function () {
var b = this.b;
var n = b.length;
var b2j = this.b2j = {};
var populardict = {};
for (var i = 0; i < b.length; i++) {
var elt = b[i];
if (b2j.hasOwnProperty(elt)) {
var indices = b2j[elt];
if (n >= 200 && indices.length * 100 > n) {
populardict[elt] = 1;
delete b2j[elt];
} else {
indices.push(i);
}
} else {
b2j[elt] = [i];
}
}
for (var elt in populardict) {
if (populardict.hasOwnProperty(elt)) {
delete b2j[elt];
}
}
var isjunk = this.isjunk;
var junkdict = {};
if (isjunk) {
for (var elt in populardict) {
if (populardict.hasOwnProperty(elt) && isjunk(elt)) {
junkdict[elt] = 1;
delete populardict[elt];
}
}
for (var elt in b2j) {
if (b2j.hasOwnProperty(elt) && isjunk(elt)) {
junkdict[elt] = 1;
delete b2j[elt];
}
}
}
this.isbjunk = difflib.__isindict(junkdict);
this.isbpopular = difflib.__isindict(populardict);
}
this.find_longest_match = function (alo, ahi, blo, bhi) {
var a = this.a;
var b = this.b;
var b2j = this.b2j;
var isbjunk = this.isbjunk;
var besti = alo;
var bestj = blo;
var bestsize = 0;
var j = null;
var k;
var j2len = {};
var nothing = [];
for (var i = alo; i < ahi; i++) {
var newj2len = {};
var jdict = difflib.__dictget(b2j, a[i], nothing);
for (var jkey in jdict) {
if (jdict.hasOwnProperty(jkey)) {
j = jdict[jkey];
if (j < blo) continue;
if (j >= bhi) break;
newj2len[j] = k = difflib.__dictget(j2len, j - 1, 0) + 1;
if (k > bestsize) {
besti = i - k + 1;
bestj = j - k + 1;
bestsize = k;
}
}
}
j2len = newj2len;
}
while (besti > alo && bestj > blo && !isbjunk(b[bestj - 1]) && a[besti - 1] == b[bestj - 1]) {
besti--;
bestj--;
bestsize++;
}
while (besti + bestsize < ahi && bestj + bestsize < bhi &&
!isbjunk(b[bestj + bestsize]) &&
a[besti + bestsize] == b[bestj + bestsize]) {
bestsize++;
}
while (besti > alo && bestj > blo && isbjunk(b[bestj - 1]) && a[besti - 1] == b[bestj - 1]) {
besti--;
bestj--;
bestsize++;
}
while (besti + bestsize < ahi && bestj + bestsize < bhi && isbjunk(b[bestj + bestsize]) &&
a[besti + bestsize] == b[bestj + bestsize]) {
bestsize++;
}
return [besti, bestj, bestsize];
}
this.get_matching_blocks = function () {
if (this.matching_blocks != null) return this.matching_blocks;
var la = this.a.length;
var lb = this.b.length;
var queue = [[0, la, 0, lb]];
var matching_blocks = [];
var alo, ahi, blo, bhi, qi, i, j, k, x;
while (queue.length) {
qi = queue.pop();
alo = qi[0];
ahi = qi[1];
blo = qi[2];
bhi = qi[3];
x = this.find_longest_match(alo, ahi, blo, bhi);
i = x[0];
j = x[1];
k = x[2];
if (k) {
matching_blocks.push(x);
if (alo < i && blo < j)
queue.push([alo, i, blo, j]);
if (i+k < ahi && j+k < bhi)
queue.push([i + k, ahi, j + k, bhi]);
}
}
matching_blocks.sort(difflib.__ntuplecomp);
var i1 = 0, j1 = 0, k1 = 0, block = 0;
var i2, j2, k2;
var non_adjacent = [];
for (var idx in matching_blocks) {
if (matching_blocks.hasOwnProperty(idx)) {
block = matching_blocks[idx];
i2 = block[0];
j2 = block[1];
k2 = block[2];
if (i1 + k1 == i2 && j1 + k1 == j2) {
k1 += k2;
} else {
if (k1) non_adjacent.push([i1, j1, k1]);
i1 = i2;
j1 = j2;
k1 = k2;
}
}
}
if (k1) non_adjacent.push([i1, j1, k1]);
non_adjacent.push([la, lb, 0]);
this.matching_blocks = non_adjacent;
return this.matching_blocks;
}
this.get_opcodes = function () {
if (this.opcodes != null) return this.opcodes;
var i = 0;
var j = 0;
var answer = [];
this.opcodes = answer;
var block, ai, bj, size, tag;
var blocks = this.get_matching_blocks();
for (var idx in blocks) {
if (blocks.hasOwnProperty(idx)) {
block = blocks[idx];
ai = block[0];
bj = block[1];
size = block[2];
tag = '';
if (i < ai && j < bj) {
tag = 'replace';
} else if (i < ai) {
tag = 'delete';
} else if (j < bj) {
tag = 'insert';
}
if (tag) answer.push([tag, i, ai, j, bj]);
i = ai + size;
j = bj + size;
if (size) answer.push(['equal', ai, i, bj, j]);
}
}
return answer;
}
// this is a generator function in the python lib, which of course is not supported in javascript
// the reimplementation builds up the grouped opcodes into a list in their entirety and returns that.
this.get_grouped_opcodes = function (n) {
if (!n) n = 3;
var codes = this.get_opcodes();
if (!codes) codes = [["equal", 0, 1, 0, 1]];
var code, tag, i1, i2, j1, j2;
if (codes[0][0] == 'equal') {
code = codes[0];
tag = code[0];
i1 = code[1];
i2 = code[2];
j1 = code[3];
j2 = code[4];
codes[0] = [tag, Math.max(i1, i2 - n), i2, Math.max(j1, j2 - n), j2];
}
if (codes[codes.length - 1][0] == 'equal') {
code = codes[codes.length - 1];
tag = code[0];
i1 = code[1];
i2 = code[2];
j1 = code[3];
j2 = code[4];
codes[codes.length - 1] = [tag, i1, Math.min(i2, i1 + n), j1, Math.min(j2, j1 + n)];
}
var nn = n + n;
var group = [];
var groups = [];
for (var idx in codes) {
if (codes.hasOwnProperty(idx)) {
code = codes[idx];
tag = code[0];
i1 = code[1];
i2 = code[2];
j1 = code[3];
j2 = code[4];
if (tag == 'equal' && i2 - i1 > nn) {
group.push([tag, i1, Math.min(i2, i1 + n), j1, Math.min(j2, j1 + n)]);
groups.push(group);
group = [];
i1 = Math.max(i1, i2-n);
j1 = Math.max(j1, j2-n);
}
group.push([tag, i1, i2, j1, j2]);
}
}
if (group && !(group.length == 1 && group[0][0] == 'equal')) groups.push(group)
return groups;
}
this.ratio = function () {
matches = difflib.__reduce(
function (sum, triple) { return sum + triple[triple.length - 1]; },
this.get_matching_blocks(), 0);
return difflib.__calculate_ratio(matches, this.a.length + this.b.length);
}
this.quick_ratio = function () {
var fullbcount, elt;
if (this.fullbcount == null) {
this.fullbcount = fullbcount = {};
for (var i = 0; i < this.b.length; i++) {
elt = this.b[i];
fullbcount[elt] = difflib.__dictget(fullbcount, elt, 0) + 1;
}
}
fullbcount = this.fullbcount;
var avail = {};
var availhas = difflib.__isindict(avail);
var matches = numb = 0;
for (var i = 0; i < this.a.length; i++) {
elt = this.a[i];
if (availhas(elt)) {
numb = avail[elt];
} else {
numb = difflib.__dictget(fullbcount, elt, 0);
}
avail[elt] = numb - 1;
if (numb > 0) matches++;
}
return difflib.__calculate_ratio(matches, this.a.length + this.b.length);
}
this.real_quick_ratio = function () {
var la = this.a.length;
var lb = this.b.length;
return _calculate_ratio(Math.min(la, lb), la + lb);
}
this.isjunk = isjunk ? isjunk : difflib.defaultJunkFunction;
this.a = this.b = null;
this.set_seqs(a, b, c);
}
};

Cant call the public method on jquery Plugin

I developed a plugin and when I call the plugin getting an error like Uncaught TypeError: Cannot read property 'convert' of undefined.
Here is my Plugin ,Its not working when I calling in my scripts
( function ($) {
$.siPrifixx = function(element, options) {
var defaults = {
foo: 'bar',
onFoo: function() {
}
}
var plugin = this;
plugin.settings = {
maxDigits: 8,
seperator: true,
decimal: 1,
popUp: false,
countUp:false
}
var $element = $(element),
element = element;
plugin.init = function() {
var value =$(element);
console.log(value);
plugin.settings = $.extend({
}, defaults, options);
var maxDigits = plugin.settings.maxDigits;
console.log(defaults);
if (typeof value === 'string') {
var parts = value.split(",");
var num = parts.join("");
var isNumber = regIsNumber(num)
if(isNumber){
var number = (parseInt(num));
}else{
number = num;
}
}else if (typeof value === 'number'){
number = value
}
var data_max = $(this).attr('data-max-digit');
if(typeof data_max !== 'undefined'){
maxDigits = data_max;
}
var checkNumber = typeof number !== 'undefined' && !isNaN(number) && Math.round(number).toString().length > maxDigits;
if (plugin.settings.popUp && checkNumber) {
$(this).addClass('tooltip', value);
var tootip = $(this).tooltipster({
theme: 'tooltipster-default',
functionInit: function () {
return value
}
})
if(!tootip)
console.log("We couldn't find tooltipster function.Please make sure you have loaded the plugin")
}
if (plugin.settings.countUp && (Math.round(value).toString().length <= maxDigits)) {
var cUp = new countUp(
plugin.settings.countUp, 0, Number(value), 0, 1, null);
cUp.start();
if(!cUp)
console.log("We couldn't find counter function.Please make sure you have loaded the plugin")
}
if (checkNumber) {
var results = plugin.convert(number);
$(this).html(results);
} else {
if (plugin.settings.seperator) {
var cvalue = numberWithCommas(value)
$(this).html(cvalue)
} else {
$(this).html(value)
}
if(typeof value === 'string')
if(checkDate(value)){
$(this).html(value)
}
}
}
plugin.convert = function(number){
var n = settings.decimal
var decPlace = Math.pow(10, n);
var abbrev = ["K", "M", "B", "T"];
for (var i = abbrev.length - 1; i >= 0; i--) {
var size = Math.pow(10, (i + 1) * 3);
if (size <= number) {
number = Math.round(number * decPlace / size) / decPlace;
if ((number == 1000) && (i < abbrev.length - 1)) {
number = 1;
i++;
}
number += abbrev[i];
break;
}
}
console.log(number);
return number;
}
plugin.init();
//use to convert numbers with comma seperated
}
$.fn.siPrifixx = function (options) {
return this.each(function() {
if (undefined == $(this).data('siPrifixx')) {
var plugin = new $.siPrifixx(this,options);
$(this).data('siPrifixx', plugin);
}
});
};
}(jQuery));
I use to call the plugin by $(this).data('siPrifixx').convert(value);});
What is the problem with my code?How can I modify my plugin to gets works?
How can I call convert method in code.
One approach would be to divide plugin into individual portion which each return expected result, then merge the discrete working portions one by one until the full plugin in functional
(function($) {
var settings = {
maxDigits: 8,
seperator: true,
decimal: 0,
popUp: false,
countUp: false
}
function convert(number, options) {
var opts = $.extend(settings, options || {});
var n = opts.decimal;
console.log(opts);
var decPlace = Math.pow(10, n);
var abbrev = ["K", "M", "B", "T"];
for (var i = abbrev.length - 1; i >= 0; i--) {
var size = Math.pow(10, (i + 1) * 3);
if (size <= number) {
number = Math.round(number * decPlace / size) / decPlace;
if ((number == 1000) && (i < abbrev.length - 1)) {
number = 1;
i++;
}
number += abbrev[i];
break;
}
}
this.data("number", number); // set `number` at `.data("number")`
return this; // return `this` for chaining jQuery methods
}
$.fn.convert = convert;
}(jQuery));
var div = $("div");
div.convert(1500000, {decimal:1});
console.log(div.data("number"))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
You should call it like this:
$(this).data('siPrifixx').plugin.convert(value);});

Autocompleter Javascript-for Wordpress site

I need help ...
I have an autocomplete plugin that installed on my site and it works perfect...My need for autocomplete was bacause i have posts to which i want to redirect when clicked on autocompleted list item .
for example : i have one search form and when typed and autococompleted some post name then it redirects me to post like example.com/post/namePost .Now i cloned that website and my new website is example1.com ... now autocompleter in new site redirects me on autocomplete to example1.com/post/namePost .
My problem is , that i need that autocompleter on new site,redirects me to old website link - in this case www.example.com/post/postName. Note that after www.example.com both url data is same
Here is my autocomplete.js code :
/*
original jQuery plugin by http://www.pengoworks.com/workshop/jquery/autocomplete.htm
just replaced $ with jQuery in order to be complaint with other JavaScript libraries.
*/
jQuery.autocomplete = function(input, options) {
// Create a link to self
var me = this;
var link="http://telecoms-group.com/";
// Create jQuery object for input element
var $input = jQuery(input).attr("autocomplete", "off");
// Apply inputClass if necessary
if (options.inputClass) $input.addClass(options.inputClass);
// Create results
var results = document.createElement("div");
// Create jQuery object for results
var $results = jQuery(results);
$results.hide().addClass(options.resultsClass).css("position", "absolute");
if( options.width > 0 ) $results.css("width", options.width);
// Add to body element
jQuery("body").append(results);
input.autocompleter = me;
var timeout = null;
var prev = "";
var active = -1;
var cache = {};
var keyb = false;
var hasFocus = false;
var lastKeyPressCode = null;
// flush cache
function flushCache(){
cache = {};
cache.data = {};
cache.length = 0;
};
// flush cache
flushCache();
// if there is a data array supplied
if( options.data != null ){
var sFirstChar = "", stMatchSets = {}, row = [];
// no url was specified, we need to adjust the cache length to make sure it fits the local data store
if( typeof options.url != "string" ) options.cacheLength = 1;
// loop through the array and create a lookup structure
for( var i=0; i < options.data.length; i++ ){
// if row is a string, make an array otherwise just reference the array
row = ((typeof options.data[i] == "string") ? [options.data[i]] : options.data[i]);
// if the length is zero, don't add to list
if( row[0].length > 0 ){
// get the first character
sFirstChar = row[0].substring(0, 1).toLowerCase();
// if no lookup array for this character exists, look it up now
if( !stMatchSets[sFirstChar] ) stMatchSets[sFirstChar] = [];
// if the match is a string
stMatchSets[sFirstChar].push(row);
}
}
// add the data items to the cache
for( var k in stMatchSets ){
// increase the cache size
options.cacheLength++;
// add to the cache
addToCache(k, stMatchSets[k]);
}
}
$input
.keydown(function(e) {
// track last key pressed
lastKeyPressCode = e.keyCode;
switch(e.keyCode) {
case 38: // up
e.preventDefault();
moveSelect(-1);
break;
case 40: // down
e.preventDefault();
moveSelect(1);
break;
case 9: // tab
case 13: // return
if( selectCurrent() ){
// make sure to blur off the current field
$input.get(0).blur();
e.preventDefault();
}
break;
default:
active = -1;
if (timeout) clearTimeout(timeout);
timeout = setTimeout(function(){onChange();}, options.delay);
break;
}
})
.focus(function(){
// track whether the field has focus, we shouldn't process any results if the field no longer has focus
hasFocus = true;
})
.blur(function() {
// track whether the field has focus
hasFocus = false;
hideResults();
});
hideResultsNow();
function onChange() {
// ignore if the following keys are pressed: [del] [shift] [capslock]
if( lastKeyPressCode == 46 || (lastKeyPressCode > 8 && lastKeyPressCode < 32) ) return $results.hide();
var v = $input.val();
if (v == prev) return;
prev = v;
if (v.length >= options.minChars) {
$input.addClass(options.loadingClass);
requestData(v);
} else {
$input.removeClass(options.loadingClass);
$results.hide();
}
};
function moveSelect(step) {
var lis = jQuery("li", results);
if (!lis) return;
active += step;
if (active < 0) {
active = 0;
} else if (active >= lis.size()) {
active = lis.size() - 1;
}
lis.removeClass("ac_over");
jQuery(lis[active]).addClass("ac_over");
// Weird behaviour in IE
// if (lis[active] && lis[active].scrollIntoView) {
// lis[active].scrollIntoView(false);
// }
};
function selectCurrent() {
var li = jQuery("li.ac_over", results)[0];
if (!li) {
var $li = jQuery("li", results);
if (options.selectOnly) {
if ($li.length == 1) li = $li[0];
} else if (options.selectFirst) {
li = $li[0];
}
}
if (li) {
selectItem(li);
return true;
} else {
return false;
}
};
function selectItem(li) {
if (!li) {
li = document.createElement("li");
li.extra = [];
li.selectValue = "";
}
var v = jQuery.trim(li.selectValue ? li.selectValue : li.innerHTML);
input.lastSelected = v;
prev = v;
$results.html("");
$input.val(v);
hideResultsNow();
if (options.onItemSelect) setTimeout(function() { options.onItemSelect(li) }, 1);
};
// selects a portion of the input string
function createSelection(start, end){
// get a reference to the input element
var field = $input.get(0);
if( field.createTextRange ){
var selRange = field.createTextRange();
selRange.collapse(true);
selRange.moveStart("character", start);
selRange.moveEnd("character", end);
selRange.select();
} else if( field.setSelectionRange ){
field.setSelectionRange(start, end);
} else {
if( field.selectionStart ){
field.selectionStart = start;
field.selectionEnd = end;
}
}
field.focus();
};
// fills in the input box w/the first match (assumed to be the best match)
function autoFill(sValue){
// if the last user key pressed was backspace, don't autofill
if( lastKeyPressCode != 8 ){
// fill in the value (keep the case the user has typed)
$input.val($input.val() + sValue.substring(prev.length));
// select the portion of the value not typed by the user (so the next character will erase)
createSelection(prev.length, sValue.length);
}
};
function showResults() {
// get the position of the input field right now (in case the DOM is shifted)
var pos = findPos(input);
// either use the specified width, or autocalculate based on form element
var iWidth = (options.width > 0) ? options.width : $input.width();
// reposition
$results.css({
width: parseInt($input.width()+15)+ "px",
top: (pos.y + input.offsetHeight+ input.offsetHeight) + "px",
left: pos.x + "px"
}).show();
};
function hideResults() {
if (timeout) clearTimeout(timeout);
timeout = setTimeout(hideResultsNow, 200);
};
function hideResultsNow() {
if (timeout) clearTimeout(timeout);
$input.removeClass(options.loadingClass);
if ($results.is(":visible")) {
$results.hide();
}
if (options.mustMatch) {
var v = $input.val();
if (v != input.lastSelected) {
selectItem(null);
}
}
};
function receiveData(q, data) {
if (data) {
$input.removeClass(options.loadingClass);
results.innerHTML = "";
// if the field no longer has focus or if there are no matches, do not display the drop down
if( !hasFocus || data.length == 0 ) return hideResultsNow();
if (jQuery.browser.msie) {
// we put a styled iframe behind the calendar so HTML SELECT elements don't show through
$results.append(document.createElement('iframe'));
}
results.appendChild(dataToDom(data));
// autofill in the complete box w/the first match as long as the user hasn't entered in more data
if( options.autoFill && ($input.val().toLowerCase() == q.toLowerCase()) ) autoFill(data[0][0]);
showResults();
} else {
hideResultsNow();
}
};
function parseData(data) {
if (!data) return null;
var parsed = [];
var rows = data.split(options.lineSeparator);
for (var i=0; i < rows.length; i++) {
var row = jQuery.trim(rows[i]);
if (row) {
parsed[parsed.length] = row.split(options.cellSeparator);
}
}
return parsed;
};
function dataToDom(data) {
var ul = document.createElement("ul");
var num = data.length;
// limited results to a max number
if( (options.maxItemsToShow > 0) && (options.maxItemsToShow < num) ) num = options.maxItemsToShow;
for (var i=0; i < num; i++) {
var row = data[i];
if (!row) continue;
var li = document.createElement("li");
if (options.formatItem) {
li.innerHTML = options.formatItem(row, i, num);
li.selectValue = row[0];
} else {
li.innerHTML = row[0];
li.selectValue = row[0];
}
var extra = null;
if (row.length > 1) {
extra = [];
for (var j=1; j < row.length; j++) {
extra[extra.length] = row[j];
}
}
li.extra = extra;
ul.appendChild(li);
jQuery(li).hover(
function() { jQuery("li", ul).removeClass("ac_over"); jQuery(this).addClass("ac_over"); active = jQuery("li", ul).indexOf(jQuery(this).get(0)); },
function() { jQuery(this).removeClass("ac_over"); }
).click(function(e) { e.preventDefault(); e.stopPropagation(); selectItem(this) });
}
return ul;
};
function requestData(q) {
if (!options.matchCase) q = q.toLowerCase();
var data = options.cacheLength ? loadFromCache(q) : null;
// recieve the cached data
if (data) {
receiveData(q, data);
// if an AJAX url has been supplied, try loading the data now
} else if( (typeof options.url == "string") && (options.url.length > 0) ){
jQuery.get(makeUrl(q), function(data) {
data = parseData(data);
addToCache(q, data);
receiveData(q, data);
});
// if there's been no data found, remove the loading class
} else {
$input.removeClass(options.loadingClass);
}
};
function makeUrl(q) {
var url = options.url + "?q=" + encodeURI(q);
for (var i in options.extraParams) {
url += "&" + i + "=" + encodeURI(options.extraParams[i]);
}
return url;
};
function loadFromCache(q) {
if (!q) return null;
if (cache.data[q]) return cache.data[q];
if (options.matchSubset) {
for (var i = q.length - 1; i >= options.minChars; i--) {
var qs = q.substr(0, i);
var c = cache.data[qs];
if (c) {
var csub = [];
for (var j = 0; j < c.length; j++) {
var x = c[j];
var x0 = x[0];
if (matchSubset(x0, q)) {
csub[csub.length] = x;
}
}
return csub;
}
}
}
return null;
};
function matchSubset(s, sub) {
if (!options.matchCase) s = s.toLowerCase();
var i = s.indexOf(sub);
if (i == -1) return false;
return i == 0 || options.matchContains;
};
this.flushCache = function() {
flushCache();
};
this.setExtraParams = function(p) {
options.extraParams = p;
};
this.findValue = function(){
var q = $input.val();
if (!options.matchCase) q = q.toLowerCase();
var data = options.cacheLength ? loadFromCache(q) : null;
if (data) {
findValueCallback(q, data);
} else if( (typeof options.url == "string") && (options.url.length > 0) ){
jQuery.get(makeUrl(q), function(data) {
data = parseData(data)
addToCache(q, data);
findValueCallback(q, data);
});
} else {
// no matches
findValueCallback(q, null);
}
}
function findValueCallback(q, data){
if (data) $input.removeClass(options.loadingClass);
var num = (data) ? data.length : 0;
var li = null;
for (var i=0; i < num; i++) {
var row = data[i];
if( row[0].toLowerCase() == q.toLowerCase() ){
li = document.createElement("li");
if (options.formatItem) {
li.innerHTML = options.formatItem(row, i, num);
li.selectValue = row[0];
} else {
li.innerHTML = row[0];
li.selectValue = row[0];
}
var extra = null;
if( row.length > 1 ){
extra = [];
for (var j=1; j < row.length; j++) {
extra[extra.length] = row[j];
}
}
li.extra = extra;
}
}
if( options.onFindValue ) setTimeout(function() { options.onFindValue(li) }, 1);
}
function addToCache(q, data) {
if (!data || !q || !options.cacheLength) return;
if (!cache.length || cache.length > options.cacheLength) {
flushCache();
cache.length++;
} else if (!cache[q]) {
cache.length++;
}
cache.data[q] = data;
};
function findPos(obj) {
var curleft = obj.offsetLeft || 0;
var curtop = obj.offsetTop || 0;
while (obj = obj.offsetParent) {
curleft += obj.offsetLeft
curtop += obj.offsetTop
}
return {x:curleft,y:curtop};
}
}
jQuery.fn.autocomplete = function(url, options, data) {
// Make sure options exists
options = options || {};
// Set url as option
options.url = url;
// set some bulk local data
options.data = ((typeof data == "object") && (data.constructor == Array)) ? data : null;
// Set default values for required options
options.inputClass = options.inputClass || "ac_input";
options.resultsClass = options.resultsClass || "ac_results";
options.lineSeparator = options.lineSeparator || "\n";
options.cellSeparator = options.cellSeparator || "|";
options.minChars = options.minChars || 1;
options.delay = options.delay || 400;
options.matchCase = options.matchCase || 0;
options.matchSubset = options.matchSubset || 1;
options.matchContains = options.matchContains || 0;
options.cacheLength = options.cacheLength || 1;
options.mustMatch = options.mustMatch || 0;
options.extraParams = options.extraParams || {};
options.loadingClass = options.loadingClass || "ac_loading";
options.selectFirst = options.selectFirst || false;
options.selectOnly = options.selectOnly || false;
options.maxItemsToShow = options.maxItemsToShow || -1;
options.autoFill = options.autoFill || false;
options.width = parseInt(options.width, 10) || 0;
this.each(function() {
var input = this;
new jQuery.autocomplete(input, options);
});
// Don't break the chain
return this;
}
jQuery.fn.autocompleteArray = function(data, options) {
return this.autocomplete(null, options, data);
}
jQuery.fn.indexOf = function(e){
for( var i=0; i<this.length; i++ ){
if( this[i] == e ) return i;
}
return -1;
};
Can somebody tell me where is that part with url redirection , and how can i change that

getNodeById does not work

I have a ext treepanel with json.
var tree = new Ext.tree.TreePanel({
renderTo:'tree-container',
title: 'Category',
height: 300,
width: 400,
useArrows:true,
autoScroll:true,
animate:true,
enableDD:true,
containerScroll: true,
rootVisible: false,
frame: true,
root: {
text: 'Category',
draggable: false,
id: '0'
},
// auto create TreeLoader
dataUrl: $("#web").val() + "/category/index/get-nodes",
listeners: {
'checkchange': function(node, checked){
if(checked){
categoryManager.add(node.id);
//node.getUI().addClass('complete');
}else{
categoryManager.remove(node.id);
// node.getUI().removeClass('complete');
}
}
}
});
dataUrl loads the following json code
[{"text":"Code Snippet","id":"1","cls":"folder","checked":false,"children":[{"text":"PHP","id":"3","cls":"file","checked":false,"children":[]},{"text":"Javascript","id":"4","cls":"file","checked":false,"children":[]}]}]
when I try to find a node by console.log( tree.getNodeByid(3) ), it shows that it is undefined.
Do I have a problem with my code?
tree.getNodeById(...) find only node that expanded
you can find the node path as follow, and than expand the paths and get the node
var MyTree = Ext.extend(Ext.tree.TreePanel, {
getPath : function(id){
var node = this.getNodeById(id);
if(node){
return node.getPath();
}
var paths = this.root.getPath();
forEach = function(list, fun, sope){
if(!list || list.length == 0){
return;
}
for(var i = 0, length = list.length; i < length; i++){
var node = list[i];
var args = [];
args.push(node);
if(arguments.length > 3){
for(var ii = 3; ii < arguments.length; ii++){
args.push(arguments[ii]);
}
}
var result = fun.apply(sope, args);
if(result){
return result;
}
}
};
getChildNodes = function(parent){
var children = parent.children || parent.childNodes;
if(children && children.length == 0 && parent.attributes){
children = parent.attributes.children;
}
return children;
};
getPath = function(item, paths){
if(item.id == id){
return paths + "/" + item.id;
}
return forEach(getChildNodes(item), getPath, this, paths + "/" + item.id);
};
return forEach(getChildNodes(this.root), getPath, this, paths);
}
});
var tree = new MyTree(....);
var paths = tree.getPath(id);
if(paths){
this.expandPath(paths);
var node = tree.getNodeById(id);
}

Categories

Resources