Dojo.Connect with click event for div element inside loop - for-loop

I'm trying to show alert message including click event on div element that are sought through a loop. The problem is that in any div I click, it is only displayed the alert of the last element. How can I solve? I do not understand the logic being performed.
for (var i = 0; i < this.legend.layerInfos.length; i++)
{
var sNomeDiv = "";
var sMensagem = "";
if (this.legend.layerInfos[i].layer.visible)
{
sNomeDiv = this.legend.id + "_" + this.legend.layerInfos[i].layer.id;
if (this.legend.layerInfos[i].layer.description == "" || this.legend.layerInfos[i].layer.description == "undefined" || this.legend.layerInfos[i].layer.description == "null")
{
sMensagem = "Nenhuma informação cadastrada para a camada " + this.legend.layerInfos[i].title;
}
else
{
sMensagem = this.legend.layerInfos[i].layer.description;
}
//Always display an alert with the text of the last element of the loop
dojo.connect
(
dojo.byId(sNomeDiv),
"onclick",
function()
{
alert(sMensagem + " --> " + sNomeDiv);
}
);
}
}

Related

how to restrict double extension while uploading file to server

fileName = inputParam.file_name.split('.')[0].toLowerCase().replace(/ /g, '') + '' + Date.now() + "." + (fileData.file.name.split('.')[1] || inputParam.file_name.split('.')[1])
filePath = filePath + fileName
This is the condition I am using.
For example it should only restrict a.jpeg.jpg or a.php.jpeg. and allow extension like a.a.jpeg or bird.tree.jpeg
var _validFilejpeg = [".jpeg", ".jpg", ".bmp", ".png",".pdf", ".txt"];
var invalid = [".php",".php5", ".pht", ".phtml", ".shtml", ".asa", ".cer", ".asax", ".swf",".xap"];
function validateForSize(oInput, minSize, maxSizejpeg) {
//if there is a need of specifying any other type, just add that particular type in var _validFilejpeg
if (oInput.type == "file") {
var sFileName = oInput.value;
var file = sFileName.match(/\d/g);
var fileExt = sFileName.substr(sFileName.length-4);
if (sFileName.length > 0) {
var blnValid = false;
for (var j = 0; j < _validFilejpeg.length; j++) {
var sCurExtension = _validFilejpeg[j];
if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length)
.toLowerCase() == sCurExtension.toLowerCase()) {
blnValid = true;
break;
}
}
if(fileExt = 'invalid'){
alert("Your document does not have a proper file extension.")
blnValid = false;
}
if(fileExt = 'file'){
alert("Your document does not have a proper file extension.")
blnValid = false;
}
if (!blnValid) {
alert("Sorry, this file is invalid, allowed extension is: " + _validFilejpeg.join(", "));
oInput.value = "";
return false;
}
}
}
fileSizeValidatejpeg(oInput, minSize, maxSizejpeg);
}
function fileSizeValidatejpeg(fdata, minSize, maxSizejpeg) {
if (fdata.files && fdata.files[0]) {
var fsize = fdata.files[0].size /1024; //The files property of an input element returns a FileList. fdata is an input element,fdata.files[0] returns a File object at the index 0.
//alert(fsize)
if (fsize > maxSizejpeg || fsize < minSize) {
alert('This file size is: ' + fsize.toFixed(2) +
"KB. Files should be in " + (minSize) + " to " + (maxSizejpeg) + " KB ");
fdata.value = ""; //so that the file name is not displayed on the side of the choose file button
return false;
} else {
console.log("");
}
}
}
<input type="file" onchange="validateForSize(this,20,5000);" >
You can simply do this
if (fileName.split('.').length > 2) {
throw new Error('Double extension file detected')
}

Edit UI bot framework

I read here that it was possible to display a message when the cursor is on a button of a promt. I looked a little on the net but I did not find what part of the botchat.js edit.
Can you teach me?
Thanks you
display a message when the cursor is on a button of a promt.
You could modify the botchat.js file to add title attribute to the button in order to shown it as a tooltip text when the mouse moves over the button, the following code snippet is for your reference.
Add add title attribute to actionButton element within ActionCollection.prototype.render function:
for (var i = 0; i < this.items.length; i++) {
if (isActionAllowed(this.items[i], forbiddenActionTypes)) {
var actionButton = new ActionButton(this.items[i]);
actionButton.element.style.overflow = "hidden";
actionButton.element.style.overflow = "table-cell";
actionButton.element.style.flex = this._owner.hostConfig.actions.actionAlignment === Enums.ActionAlignment.Stretch ? "0 1 100%" : "0 1 auto";
/*add title attribute to button*/
actionButton.element.title = this.items[i].title;
actionButton.text = this.items[i].title;
actionButton.onClick = function (ab) { _this.actionClicked(ab); };
this._actionButtons.push(actionButton);
buttonStrip.appendChild(actionButton.element);
this._renderedActionCount++;
if (this._renderedActionCount >= this._owner.hostConfig.actions.maxActions || i == this.items.length - 1) {
break;
}
else if (this._owner.hostConfig.actions.buttonSpacing > 0) {
var spacer = document.createElement("div");
if (orientation === Enums.Orientation.Horizontal) {
spacer.style.flex = "0 0 auto";
spacer.style.width = this._owner.hostConfig.actions.buttonSpacing + "px";
}
else {
spacer.style.height = this._owner.hostConfig.actions.buttonSpacing + "px";
}
Utils.appendChild(buttonStrip, spacer);
}
}
}
Test result:

react native maps populate markers from array

I am trying to render markers on the map dynamically with the end goal of markers being able to be created and destroyed at will while the application is running. Everything is working fine, except for one small section which is this:
for (j = 0; j < markersArray.length; j ++) {
console.log("Data: J=" + j + ", " + markersArray[j].key + ", " + markersArray[j].location[0] + ", " + markersArray[j].location[1] + ", " + markersArray[j].contactName);
return <MapView.Marker
key = { markersArray[j].key }
coordinate = {{
latitude: markersArray[j].location[0],
longitude: markersArray[j].location[1]
}}
title = { markersArray[j].contactName }
/>
}
The problem here is that the array has two or more objects inside it, but will only ever go through the loop once, where j = 0. It never goes through the loop another time. My thoughts are because the word "return" is used so that I can render the marker. Is there a way around this? All the data is perfect, it simply won't loop through more than the first time.
For the pedants among you who want the whole render function ;) :
render() {
return (
<MapContainer>
<MapView
style = { styles.map }
region = { this.state.mapRegion }
showsUserLocation = { true }
followUserLocation = { true }
onRegionChangeComplete = { this.onRegionChangeComplete.bind(this) }>
<MapView.Circle
key = { (this.state.currentLongitude + this.state.currentLongitude).toString() }
center = { userPosition }
radius = { RADIUS }
strokeWidth = { 1 }
strokeColor = { '#ffffff' }
fillColor = { 'rgba(210,218,215,0.5)' }
onRegionChangeComplete = { this.onRegionChangeComplete.bind(this) }
/>
{(() => {
console.log("Map Markers polling for data...");
if (markersArray[0] != null) {
console.log("Map Markers have found data");
for (j = 0; j < markersArray.length; j ++) {
console.log("Data: J=" + j + ", " + markersArray[j].key + ", " + markersArray[j].location[0] + ", " + markersArray[j].location[1] + ", " + markersArray[j].contactName);
return <MapView.Marker
key = { markersArray[j].key }
coordinate = {{
latitude: markersArray[j].location[0],
longitude: markersArray[j].location[1]
}}
title = { markersArray[j].contactName }
/>
}
}
})()}
</MapView>
<MessageBar />
</MapContainer>
)
}
I believe that you need map function in order to render every object in that array.
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
{markersArray[0] != null && markersArray.map((marker, index) => (
<MapView.Marker
key = {index}
coordinate = {{
latitude: marker.location[0],
longitude: marker.location[1]
}}
title = { marker.contactName }
/>
))
}

Modifying sort columns in jqGrid

I'm having some difficulty figuring out how to programatically modify the sort definition that is sent to the server when a user clicks on a column to sort it. I have added a onSortCol function to my grid configuration. In that function, I need to check whether the "Id" column is in any sort position other than the last position. If it is, it should be removed.
Here is what I have tried:
onSortCol: function (index, iCol, sortOrder) {
var grid = $(this);
var rawSorts = index.split(",");
if (rawSorts.length > 1) {
var idFieldIndex = -1;
var processedSorts = [];
for (i = 0; i < rawSorts.length; i++) {
var currentSort = rawSorts[i].match(/[^ ]+/g);
if (idFieldIndex === -1 && currentSort[0].toUpperCase() === "ID") {
idFieldIndex = i;
}
processedSorts.push({
field: currentSort[0],
direction: currentSort[1] || sortOrder
})
}
if (idFieldIndex !== -1) {
processedSorts.splice(idFieldIndex, 1);
for (i = 0; i < processedSorts.length; i++) {
if (i + 1 < processedSorts.length) {
grid.sortGrid(processedSorts[i].field + " " + processedSorts[i].direction);
}
else {
grid.setGridParam("sortorder", processedSorts[i].direction);
grid.sortGrid(processedSorts[i].field + " ", true);
}
}
return "stop";
}
}
}
The most simple implementation seems to me the following: you don't use any sortname in the grid initially and you sort by Id on the server side if sidx is empty. It seems the only what you need to do to implement your requirements.

Set selection on tekst inside CKEditor

I'm having trouble to select text in CKEditor(3.6). As we use plain text i dont know how to use correctly the range selectors.
HTML code of the CKEditor:
<body spellcheck="false" class="rf-ed-b" contenteditable="true">
<br>
Cross those that apply:<br>
<br>
<br>
[«dummy»] If he/she is tall<br>
<br>
[«dummy»] If he/she is a male<br>
<br>
[«dummy»] If he/shi is a minor<br>
<br>
Specialties:<br>
<br>
[«dummy»] «Write here the specialties if known»<br>
<br>
<br>
«You are now done with filling in this form»<br>
</body>
With the keys 'CRTL+N' I want to go to the next filleble spot:
«[label]»
I tried stuff like:
var editor = CKEDITOR.instances['MyEditor'];
var findString = '«';
var element = editor.document.getBody();
var ranges = editor.getSelection().getRanges();
var startIndex = element.getHtml().indexOf(findString);
if (startIndex != -1) {
ranges[0].setStart(element.getFirst(), startIndex);
ranges[0].setEnd(element.getFirst(), startIndex + 5);
editor.getSelection().selectRanges([ranges[0]]);
}
Error:
Exception: Index or size is negative or greater than the allowed amount
While totally stripepd down it kinda works a bit:
var editor = CKEDITOR.instances['MyEditor'];
var ranges = editor.getSelection().getRanges();
var startIndex = 10;
if (startIndex != -1) {
ranges[0].setStart(element.getFirst(), startIndex);
ranges[0].setEnd(element.getFirst(), startIndex + 5);
editor.getSelection().selectRanges([ranges[0]]);
}
here it selects 5th till 10th char on first row.
I used the following sources:
example on Stackoverflow
Another stackoverflow example
CKEditor dom selection API
All solutions i can find work with html nodes.
How can set selection range on the '«' till next '»'
I've managed to solve this solution. Meanwhile i also upgraded CKeditor to 4.0.
This shouldnt have an impact on the solution.
It is a lot of code in JS.
On my keybinding i call the following JS function: getNextElement()
In this solution it also searches behind the cursor, this makes it possible to step through multiple find results.
Also the view gets scrolled to the next search result
var textNodes = [], scrollTo=0,ranges = [];
function getNextElement(){
var editor =null;
ranges = [];
// I dont know the ID of the editor, but i know there is only one the page
for(var i in CKEDITOR.instances){
editor = CKEDITOR.instances[i];
}
if(editor ==null){
return;
}
editor.focus();
var startRange = editor.getSelection().getRanges()[0];
var cursorData ="",cursorOffset=0,hasCursor = false;
if(startRange != null && startRange.endContainer.$.nodeType == CKEDITOR.NODE_TEXT){
cursorOffset = startRange.startOffset;
cursorData = startRange.endContainer.$.data;
hasCursor = true;
}
var element;
element = editor.document.getBody().getLast().getParent();
var selection = editor.getSelection();
// Recursively search for text nodes starting from root.
textNodes = [];
getTextNodes( element );
var foundElement = false;
foundElement = iterateEditor(editor,hasCursor,cursorData,cursorOffset);
if(!foundElement){
foundElement =iterateEditor(editor,false,"",0);
}
if(foundElement){
// Select the range with the first << >>.
selection.selectRanges( ranges );
jQuery(".cke_wysiwyg_frame").contents().scrollTop(scrollTo);
}
}
function iterateEditor(editor,hasCursor,cursorData,cursorOffset){
var foundElement = false;
var rowNr = 0;
var text, range;
var foundNode = false;
if(!hasCursor){
foundNode = true;
}
// Iterate over and inside the found text nodes. If some contains
// phrase "<< >>", create a range that selects this word.
for (var i = textNodes.length; i--; ) {
text = textNodes[ i ];
if ( text.type == CKEDITOR.NODE_ELEMENT && text.getName() == "br" ){
rowNr++;
} else if ( text.type == CKEDITOR.NODE_TEXT ) {
var sameNode = false;
if(text.$.data == cursorData){
foundNode = true;
sameNode = true;
}
if(foundNode){
var startIndex = -1;
var endIndex = 1;
if(sameNode){
// Check inside the already selected node if the text has multiple hits on the searchphrase
var indicesStart = getIndicesOf('\u00AB', text.getText());
var indicesEnd = getIndicesOf('\u00BB', text.getText());
for (var j = indicesStart.length; j--; ) {
if(indicesStart[j] > cursorOffset){
startIndex = indicesStart[j];
endIndex = indicesEnd[j];
}
}
} else{
startIndex = text.getText().indexOf( '\u00AB' );
endIndex = text.getText().indexOf( '\u00BB' );
}
if ( startIndex > -1 && (!sameNode || startIndex > cursorOffset)) {
range = editor.createRange();
range.setStart( text, startIndex );
foundElement = true;
// calculate the height the window should scroll to focus the selected element
scrollTo = (rowNr)*20;
}
if ( endIndex > -1 && foundElement ) {
range.setEnd( text, endIndex+1 );
ranges.push( range );
return true;
}
}
}
}
}
function getIndicesOf(searchStr, str) {
var startIndex = 0, searchStrLen = searchStr.length;
var index, indices = [];
while ((index = str.indexOf(searchStr, startIndex)) > -1) {
indices.push(index);
startIndex = index + searchStrLen;
}
return indices;
}
function getTextNodes( element ) {
var children = element.getChildren(), child;
for ( var i = children.count(); i--; ) {
child = children.getItem( i );
textNodes.push( child );
}
}

Resources