How can i use multiple pagedown in one page? - javascript

I tried the below code for that, but it adds pagedown buttons to only the first .wmd-input.
if ($(".wmd-input").length > 0) {
var converter = new Markdown.Converter();
var help = function () { alert("Do you need help?"); }
var options = {
helpButton: { handler: help },
strings: {quoteexample: "whatever you're quoting, put it right here"}
};
var editors = [];
var i = 0;
$(".wmd-input").each(function() {
editors[i] = new Markdown.Editor(converter, "", options);
editors[i].run();
i = i + 1;
});
}

Looks like i have to add unique ID for each element of wmd. I mean wmd-input, wmd-preview and wmd-button-bar. I modified this id attributes programmatically. This can be done with modifying manually but my length of inputs are dynamic.
// make wmd's id's unique
var pBox = $(this).parents(".box");
$(pBox).find("textarea").attr('id', "wmd-input" + i);
$(pBox).children("#wmd-preview").attr('id', "wmd-preview" + i);
$(pBox).find("#wmd-button-bar").attr('id', "wmd-button-bar" + i);
So when this ID attributes is set, i called the editor with postfix variable and problem solved.
editors[i] = new Markdown.Editor(converters[i], i, options);
if ($(".wmd-input").length > 0) {
var converters = [];
var editors = [];
var i = 1;
$(".wmd-input").each(function() {
converters[i] = new Markdown.Converter();
var help = function () { alert("Do you need help?"); }
var options = {
helpButton: { handler: help },
strings: {quoteexample: "whatever you're quoting, put it right here"}
};
// make wmd's id's unique
var pBox = $(this).parents(".box");
$(pBox).find("textarea").attr('id', "wmd-input" + i);
$(pBox).children("#wmd-preview").attr('id', "wmd-preview" + i);
$(pBox).find("#wmd-button-bar").attr('id', "wmd-button-bar" + i);
editors[i] = new Markdown.Editor(converters[i], i, options);
editors[i].run();
i = i + 1;
});
}

Related

Rerender text with updated value in fabric js

I'm using fabricjs and want to render the text every time a value is updated.
But when I do this, the new text overlaps the old. I tried to clear the object but didn't find any way to do so.
Below is the code snippet to describe what I doing:
//console.log('topp'+ rect.getTop());
rect.on('moving', function() {
var rectTop = rect.getTop();
var upCounter = 0;
var downCounter = 0;
var text40;
var canvas_objects = canvasForRect._objects;
// console.log('topp'+ rect.getTop());
// READ STRING FROM LOCAL STORAGE
var retrievedObject = localStorage.getItem('heatMapClickData');
// CONVERT STRING TO REGULAR JS OBJECT
var text40;
var last = canvas_objects[canvas_objects.length - 1];
var parsedObject = JSON.parse(retrievedObject);
$.each(parsedObject, function(index, item) {
if (rectTop >= item['pos_y']) {
upCounter += 1;
} else {
downCounter += 1;
}
text40 = new fabric.Text("Total clicks above line" + upCounter, {
fontSize: 40
});
});
// var obj = canvasForRect.getActiveObject();
// console.log(obj);
text40.set({
text: "Total clicks above line" + upCounter
});
canvasForRect.add(text40);
// canvas.renderAll();
});
How do I re-render the text every time upCounter is updated?

How to customize autocomplete function of the CodeMirror

I want to customize an autocomplete function to Codemirror.
So I have build this code:
CodeMirror.commands.autocomplete = function (cm) {
var arrayTabNONDefault = new Array();
var stringaCampi = null;
var arrayTabellaCampo = null;
var textVal = cm.getValue();
textVal = textVal.toUpperCase();
var res = textVal.match("SELECT(.*)FROM");
if (res != null) {
stringaCampi = res[1];
arrayTabellaCampo = stringaCampi.split(",");
var nomeTab = null;
for (var i = 0; i < arrayTabellaCampo.length; i++) {
nomeTab = (arrayTabellaCampo[i].split(".")[0]).trim();
if (hintTables[nomeTab] == null)
hintTables[nomeTab] = new Array();
} //FINE FOR
} //FINE IF
CodeMirror.showHint(cm, CodeMirror.hint.sql, {
tables: hintTables
});
cm.on("beforeChange", function (cm, change) {
var before = cm.getRange({ line: 0, ch: 0 }, change.from);
var text = cm.getRange(change.from, change.to);
var after = cm.getRange(change.to, { line: cm.lineCount() + 1, ch: 0 });
if (before.indexOf("FROM") !== -1)
// alert("Ho scritto FROM");
console.log("before change", before, text, after);
});
cm.on("change", function (cm, change) {
var from = change.from;
var text = change.text.join("\n");
var removed = change.removed.join("\n");
var to = cm.posFromIndex(cm.indexFromPos(from) + text.length);
var before = cm.getRange({ line: 0, ch: 0 }, from);
var after = cm.getRange(to, { line: cm.lineCount() + 1, ch: 0 });
if (before.indexOf("FROM") !== -1)
console.log("after change", before, removed, text, after);
});
} //FINE ESTENSIONE
This is the content of hintTables
var hintTables = { "#T_TF_FilesList": ["FilesListHeaderID", "NumRecord", "FileTypeID", "FileID", "FilesListHeaderID", "NumRecord"],
"#T_TF_SelectedItems": ["EventHeaderID", "ItemType", "ItemID1", "ItemID2", "EventHeaderID", "ItemType", "ItemID1", "ItemID2"],
"#T_TFT_CacheSearchCriteriaHeaders": ["ID", "SyncDate", "FileTypeID", "CriteriaExpressionString", "CriteriaExpressionHash", "PageRecordsNumber", "PageNumber", "NumFiles"]
};
So I want that the system should propose a list of this table after I write FROM, or the system should to propose a list of stored procedures after I write EXECUTE.
It is possible to do this?
Are you trying to customize the SQL hint addon? If so, you should make changes inside sql-hint.js (under codemirror/addon/hint).
Basically what you should do is:
1.In your app.js (whatever js file for your main logic) call editor.showHint({hint: CodeMirror.hint.sql) on "change" event;
2.Inside sql-hint.js, return {list: hintTables, from: somePos, to: somePos} when the user types FROM or EXECUTE which can be detected by regular expression or inspecting the tokens at the line. I made up some code for your reference:
var cursor = editor.getCursor();
var tokenAtCursor = editor.getTokenAt(cursor);
if (tokenAtCursor.type == "FROM-and-EXECUTE")
return {list: hintTables,
from: CodeMirror.Pos(cur.line, tokenAtCursor.start),
to: CodeMirror.Pos(cur.line, tokenAtCursor.end)};
If I misunderstand your question and this answer is not helpful, please tell me and I will delete it.

Adding onclick event in JavaScript with parameters

I'm trying to make a dropdown to display the results of a request given what the user writes in a field.
The problem I'm encountering is that when I try to add an onclick event to each item in the dropdown, only the last one acts like expected.
The dropdown is a section and I try to include sections in it.
Here is the dropdown :
<section id="projectDrop">
</section>
Here is the code :
var j = 0;
var tmp;
for (var i=0;((i<infos.projects.length) && (i<5));i++)
{
if (infos.projects[i].name.toLowerCase().match(projectName.value.toLowerCase()))
{
projectDrop.innerHTML += '<section id="project' + j + '">' + infos.projects[i].name + '</section>';
tmp = document.getElementById('project' + j);
projectDrop.style.height = (j+1)*20 + 'px';
tmp.style.top = j*20 + 'px';
tmp.style.height = '20 px';
tmp.style.width = '100%';
tmp.style.color = 'rgb(0, 0, 145)';
tmp.style.textAlign = 'center';
tmp.style.cursor = 'pointer';
tmp.style.zIndex = 5;
tmp.onclick = function(name, key)
{
return function()
{
return insertProject(name, key);
};
} (infos.projects[i].name, infos.projects[i].key);
++j;
}
}
The result is visually as I expected, I can see the dropdown with all my projects listed and a pointer while hovering etc...
But only the last project is clickable and trigger the "insertProject" function while the other do nothing.
If someone could help me solve that !
You need to store the key somewhere. Take a look at the solution below, I have used the data-key attribute on the <section> to store the key.
Also note how I have changed the code to create the element object and assign its properties, instead of building a raw string of HTML. The problem with building HTML as a string is you have to worry about escaping quotes, whereas this way you don't.
var j = 0;
var tmp;
for (var i=0;((i<infos.projects.length) && (i<5));i++)
{
if (infos.projects[i].name.toLowerCase().match(projectName.value.toLowerCase()))
{
tmp = document.createElement('section');
tmp.id = "project" + j;
tmp.setAttribute('data-key', infos.projects[i].key);
tmp.innerHTML = infos.projects[i].name;
projectDrop.style.height = (j+1)*20 + 'px';
tmp.style.top = j*20 + 'px';
tmp.style.height = '20 px';
tmp.style.width = '100%';
tmp.style.color = 'rgb(0, 0, 145)';
tmp.style.textAlign = 'center';
tmp.style.cursor = 'pointer';
tmp.style.zIndex = 5;
tmp.onclick = function(){
insertProject(this.innerHTML, this.getAttribute('data-key'));
};
projectDrop.appendChild(tmp);
++j;
}
}
Change:
tmp.onclick = function(name, key)
{
return function()
{
return insertProject(name, key);
};
} (infos.projects[i].name, infos.projects[i].key);
to
tmp.onclick = function(j){
return function(name, key)
{
return function()
{
return insertProject(name, key);
};
} (infos.projects[j].name, infos.projects[j].key);
}(i)

Calling multiple functions with one button

I am trying to call two functions when only the "add" button is clicked. the problem I am having is that the final four textboxes in the calculate_balances function are not outputting their variables.
var $ = function (id) {
return document.getElementById(id);
}
// Declare Arrays to store information from Inputs //
var transactions = [];
transactions[0] = []; // holds date
transactions[1] = []; // holds transaction type
transactions[2] = []; // holds amount
// Function to print results to text area //
var update_results = function () {
var list = ""; // string variable to build output //
// check to see if arrays are empty //
if (transactions[0].length == 0) {
$("results").value = "";
} else {
list = "";
// for loop to cycle through arrays and build string for textarea output //
for (var i = 0; i < transactions[0].length; i++) {
list += transactions[0][i] + " " + transactions[1][i] + " " + transactions[2][i] + "\n";
}
// display results //
$("results").value = list;
}
}
// function to gather inputs //
var add_transaction = function () {
$("add").blur();
transactions[0][transactions[0].length] = $("date").value;
transactions[1][transactions[1].length] = $("transType").value;
transactions[2][transactions[2].length] = parseFloat( $("amount").value);
update_results();
calculate_balances();
}
// function for Calculations //
var calculate_balances = function () {
var startBal = 2000.00;
var ttlDeposits = 0;
var ttlWithdrawals = 0;
var endBal = startBal;
if (transactions[1][transactions[1].length] == "deposit")
{
ttlDeposits += transactions[2][transactions[2].length];
endBal += ttlDeposits;
}
if (transactions[1][i] == "withdrawal")
{
ttlWithdrawals += transactions[2][transactions[i]];
endBal -= ttlWithdrawals;
}
$("balStart").value = parseFloat(startBal);
$("ttlDeposits").value = parseFloat(ttlDeposits);
$("ttlWithdrawals").value = parseFloat(ttlWithdrawals);
$("balEnd").value = parseFloat(endBal);
}
window.onload = function () {
$("add").onclick = add_transaction, calculate_balances;
update_results();
}
tHank you
Edit: Did not realize the OP was NOT using jQuery. Your onclick should look like this:
$("add").onclick = function(){
add_transaction();
calculate_balances();
};
The rest here is for jQuery which is not what the OP wanted.
For setting the value of a text box with jQuery use the val() method:
$("balStart").val(parseFloat(startBal));
To call the two methods when the button is clicked:
$("add").click(function(){
add_transaction();
calculate_balances();
});

Bing Maps - removing Itinery icons

I'm tryng to create a route planner to track my running routes. Using Bing Maps, I am able to create the route, but I'm struggling to remove to default 'beginning', 'end' and 'red circle' itinery icons.
Below is my code so far (based on this link). All I basically want is my own start icon at the beginning of the route and my end icon at the end. I don't need anything else in between apart from the route line.
Any help (along with code improvement tips) gratefully received!
jQuery(function() {
GetMap();
$("#btnStartRoute").click(function() {
map.AttachEvent('onclick', StartRouting);
});
});
var map = null;
var myRoute = [];
var noOfPushPins = 0;
function GetMap() {
map = new VEMap('mapContent');
map.SetCredentials("xxxxxxxxxxxxxxxxxx");
map.LoadMap();
}
function StartRouting(e) {
var xPoint = e.mapX, yPoint = e.mapY;
var pixel = new VEPixel(xPoint, yPoint);
var LL = map.PixelToLatLong(pixel);
cornerOne = LL; //cornerOne is a global level var
var latitude = map.PixelToLatLong(pixel).Latitude;
var longitiude = map.PixelToLatLong(pixel).Longitude;
myRoute[noOfPushPins] = new VELatLong(latitude, longitiude);
noOfPushPins++;
GetRoute();
}
function GetRoute() {
var myRouteOptions = new VERouteOptions();
myRouteOptions.RouteMode = VERouteMode.Walking;
myRouteOptions.RouteColor = new VEColor(0, 102, 51, .7);
myRouteOptions.RouteCallback = RouteCallback;
map.GetDirections(myRoute, myRouteOptions);
}
function RouteCallback(route) {
var myRouteShapes = [];
var myRoutePoints = [];
var points = route.RouteLegs[0].Itinerary.Items;
$.each(points, function(i) {
var routePointCoordinates = new VELatLong(route.RouteLegs[0].Itinerary.Items[i].LatLong.Latitude, route.RouteLegs[0].Itinerary.Items[i].LatLong.Longitude);
var routePointShape = new VEShape(VEShapeType.Pushpin, routePointCoordinates);
if (i != 0) {
routePointShape.SetCustomIcon("<img id='pushPin" + noOfPushPins + "' class='pushPin' src='/Content/Images/Maps/pushPinEnd.gif'><span class='pushPinText'>" + (noOfPushPins + 1) + "</span>");
} else {
routePointShape.SetCustomIcon("<img id='pushPin" + noOfPushPins + "' class='pushPin' src='/Content/Images/Maps/pushPinStart.gif'><span class='pushPinText'>" + (noOfPushPins + 1) + "</span>");
}
myRoutePoints.push(routePointShape);
map.Clear();
map.DeleteRoute();
map.AddShape(myRoutePoints);
});
}
There's an un-documented property called "Shape" on the Itinerary object. You can hide it...
More info here: http://social.msdn.microsoft.com/Forums/en/vemapcontroldev/thread/430449d0-fde4-4adb-9132-248fa6f9db65

Categories