$('input.ISSelectSearch').each(function(i) {
var box = new Object;
box.size = 80;
box.width = 110;
//CODE CODE CODE
});
How can I access the value of box which was set in the previous iteration? Alternatively, is it possible to access it via a key of some kind?
$('input.ISSelectSearch').each(function(i) {
var box = new Object;
box.size = 80;
box.width = 110;
prevsize = $(this).box[/* previous iteration element id or name */].size
//CODE CODE CODE
});
The problem is that I need to know the data associated with each 'input.ISSelectSearch' element box so that I can change them depending on the values of the current or preceding box objects. In other words I need a connection between the element box objects so that I can specify certain changes in one based on the values of another.
you can do something like this
var pre = null;
$('input.ISSelectSearch').each(function(i) {
var box = new Object;
box.size = 80;
box.width = 110;
//condition so that first time it dosent shows an error
if(pre!=null){
//CODE
}
pre = this;
//CODE CODE CODE
});
EDIT AFTER THE COMMENT:-
probably you wanna use $.data() method
this was you can associate the data with the element
so inside the loop you can do
$('input.ISSelectSearch').each(function(i) {
var box = new Object;
box.size = 80;
box.width = 110;
$('input.ISSelectSearch').data(i,box);
//and now you can retrive the data whenevr you want
var olderObject = $('input.ISSelectSearch').data(SOME_OLDER_INDEX)
});
You can do it with index if you like
var $This = $('input.ISSelectSearch');
$This.each(function (index, value) {
var Pre;
var box = { size: 80, width: 110 };
if (index > 0) {
Pre = $This[index - 1];
//Your code hear
} else {
//otherwise
}
});
Related
I'm looping through some elements by class name, and adding event listeners to them. I then grab the id of the selected element (in this case "tom"), and want to use it to find the value of "role" in the "tom" object. I'm getting undefined? can anyone help?
var highlightArea = document.getElementsByClassName('highlightArea');
for (var i = 0; i < highlightArea.length; i++) {
highlightArea[i].addEventListener("mouseover", showPopup);
highlightArea[i].addEventListener("mouseover", hidePopup);
}
function showPopup(evt) {
var tom = { title:'tom', role:'full stack man' };
var id = this.id;
var role = id.role;
console.log(role)
}
You are not selecting the elements correctly, the class is hightlightArea and you are querying highlightArea (missing a 't'), so, no elements are found (you can easily discover that by debugging or using console.log(highlightArea) that is the variable that holds the elements found.
Just because the id of an element is the same name as a var, it doesn't mean that it have the properties or attributes of the variable... So when you get the Id, you need to check which one is and then get the variable that have the same name.
Also, you are adding the same listener two times mouseover that way, just the last would work, it means just hidePopup. I changed to mouseenter and mouseleave, this way will work correctly.
After that, you will be able to achieve your needs. Below is an working example.
var highlightArea = document.getElementsByClassName('hightlightArea');
var mypopup = document.getElementById("mypopup");
var tom = { title:'tom', role:'marketing'};
var jim = { title:'jim', role:'another role'};
for (var i = 0; i < highlightArea.length; i++) {
highlightArea[i].addEventListener("mouseenter", showPopup);
highlightArea[i].addEventListener("mouseleave", hidePopup);
}
function showPopup(evt) {
let ElemId = this.id;
let role;
let title;
if (ElemId == 'tom'){
role = tom.role;
title = tom.title;
}else if (ElemId == 'jim'){
role = jim.role;
title = jim.title;
}
let iconPos = this.getBoundingClientRect();
mypopup.innerHTML = role;
mypopup.style.left = (iconPos.right + 20) + "px";
mypopup.style.top = (window.scrollY + iconPos.top - 60) + "px";
mypopup.style.display = "block";
}
function hidePopup(evt) {
mypopup.style.display = "none";
}
<div class="hightlightArea" id="jim">Div Jim</div>
<div class="hightlightArea" id="tom">Div Tom</div>
<div id="mypopup"></div>
in your function 'showPopup' you have this:
var id = this.id
but this.id is not defined. You probably meant to write this:
var title = dom.title;
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?
I have made a todo list my with drag and drop.I can add tasks and drag them to other categories and I can even move them to another tab where my app
is running(I can move it from one chrome tab to another).Hoewever I cannot do the following.Drag one task from chrome to firefox and vice-versa.Is that possible?
Here is jsfiddle:
https://jsfiddle.net/0feq1a12/1/
And for you who want to see code right now:
//Generate a UUID per tab
//this will help us identify when a droppedTask comes from the same page or not
var uuidGenerator =(function() {
var self = {};
var lut = []; for (var i=0; i<256; i++) { lut[i] = (i<16?'0':'')+(i).toString(16); }
self.generate = function() {
var d0 = Math.random()*0xffffffff|0;
var d1 = Math.random()*0xffffffff|0;
var d2 = Math.random()*0xffffffff|0;
var d3 = Math.random()*0xffffffff|0;
return lut[d0&0xff]+lut[d0>>8&0xff]+lut[d0>>16&0xff]+lut[d0>>24&0xff]+'-'+
lut[d1&0xff]+lut[d1>>8&0xff]+'-'+lut[d1>>16&0x0f|0x40]+lut[d1>>24&0xff]+'-'+
lut[d2&0x3f|0x80]+lut[d2>>8&0xff]+'-'+lut[d2>>16&0xff]+lut[d2>>24&0xff]+
lut[d3&0xff]+lut[d3>>8&0xff]+lut[d3>>16&0xff]+lut[d3>>24&0xff];
}
return self;
})();
var tabUUID = uuidGenerator.generate();
var taskIndex = 0;
/*
* #param event A jQuery event that occurs when an .droppable is being dragged
*/
function dragStartHandler(event){
//e refers to a jQuery object
//that does not have dataTransfer property
//so we have to refer to the original javascript event
var originalEvent = event.originalEvent;
//We want to store an object that contains the task description and its id
//We will use this object to be able to move a task from one browser to another
$target = $(event.target);
var taskToMove = {
description:$target.text(),
id:$target.data("task-id"),
tabUUID:$target.data("tab-uuid")
};
originalEvent.dataTransfer.setData("application/json",JSON.stringify(taskToMove));
originalEvent.dataTransfer.effectAllowed = "move";
}
/*
* #param event A jQuery event that occurs when a .droppable as been dropped
*/
function dropHandler(event){
event.preventDefault();
event.stopPropagation();
var originalEvent = event.originalEvent;
var droppedTask = JSON.parse(originalEvent.dataTransfer.getData("application/json"));
var droppedItem;
var taskExistsInView = droppedTask["uuid"] != tabUUID;
if(taskExistsInView){
//The dragged task comes from the same page so we can remove it from its previous category
//and move it to the new one
droppedItem = $(`body [data-task-id=${droppedTask["id"]}]`);
}
else{
//Well well well
//The dragged task comes from another tab/browser
//We can't remove it but we can create it in the current window
//using the data provided from the droppedTask object
droppedItem = $(`<div class='list-group-item droppable' draggable='true'>${droppedTask['description']}</div>`);
droppedItem.data({"task-id":taskIndex++,"tab-uuid":tabUUID});
}
var category = $(this).parent(".box").data("category");
//Change the data-category-group of the dropped item
//and move it from its original position to the new one
droppedItem.data("category",category).appendTo($(this));
}
/*
* #param The id of the task we want to delete
*/
function deleteTask(taskId){
//Find the task with the given taskId
var taskToDelete = $("body").find(`[data-task-id='${taskId}']`);
//Remove it
taskToDelete.remove();
}
function createTask(taskElement){
//Creates a task div and appends
//it to its parent category
var taskId = taskElement["id"];
var taskText = taskElement["text"];
var taskCategory = taskElement["category"];
var taskToAppend = $(`<div class='list-group-item droppable' draggable='true' data-task-id='${taskId}' data-category='${taskCategory}'>${taskText}</div>`);
taskToAppend.data("tab-uuid",tabUUID);
//Find the dropTarget to append the created task
var dropTarget = $("body").find(`[data-category='${taskCategory}'] .dropTarget`);
taskToAppend.appendTo(dropTarget);
}
function saveTasks(){
var isLocalStorageSupported = !!localStorage;
if(!isLocalStorageSupported){
//localStorage is not supported so exit the function
return;
}
//Collect all tasks
var tasks = $(".droppable");
//This array will store everything needed for a task in order to be saved
var dataToStore = [];
for(var i=0,max =tasks.length;i<max;i++){
var currentTask = tasks[i];
//For each task we need to store
//its text, and its category
//It will be reassigned a unique id and a tabUUID after it is loaded back from localStorage
var taskData = {
text:$(currentTask).text(),
category:$(currentTask).data("category")
};
dataToStore[i]=taskData;
}
localStorage.setItem("taskList",JSON.stringify(dataToStore));
alert("Tasks have been saved");
}
function loadTasks(){
//Load tasks from localStorage
var isLocalStorageSupported = !!localStorage;
if(!isLocalStorageSupported || !localStorage.getItem("taskList")){
//Maybe localStorage is not supported or maybe there are no data saved
return;
}
var loadedTasksList = JSON.parse(localStorage.getItem("taskList"));
for(var i = 0,max = loadedTasksList.length;i<max;i++){
loadedTasksList[i].id = i;
createTask(loadedTasksList[i]);
}
}
$(document).ready(function(){
loadTasks();
//When a new task/item is created it is assigned a unique data attribute which is the task index
taskIndex =$(".list-group-item").length;
$("#saveTasksBtn").on("click",saveTasks);
$("#deleteAllTasksBtn").on("click",function(){
var answer = confirm("Are you sure you want to delete all tasks?");
if(answer){
$(".droppable").remove();
taskIndex = 0;
alert("Tasks removed");
}
});
$(".createTask").on("click",function(){
//Find the category in which the clicked plus symbol belongs to
var currentCategory = $(this).parent("h1").parent(".box");
var categoryId = currentCategory.data("category");
//Create a new task
var task = $(`<div class='list-group-item droppable' draggable='true' data-task-id='${taskIndex}' data-category='${categoryId}' data-tab-uuid='${tabUUID}'></div>`);
//Ask the user for a task description
var taskDescription = prompt("Enter task description");
if(taskDescription){
//If the user wants to create a non empty task
task.text(taskDescription);
taskIndex++;
}else{
//User has left the task description empty
//so exit
return;
}
//Append the new task to the clossest dropTarget
//by finding the dropTarget that is available in our currentCategory
task.appendTo(currentCategory.find(".dropTarget"));
});
$("body").on("dragstart",".droppable",dragStartHandler);
$("body").on("dblclick",".droppable",function(){
//Ask the user for a new task description
var newTaskDescription = prompt("Enter a new description for this task");
if(newTaskDescription){
//Update the task description
$(this).text(newTaskDescription);
}
});
$(".dropTarget").on("dragenter",function(event){
event.preventDefault();
event.stopPropagation();
}).on("dragover",false)
.on("drop",dropHandler);
$("#dangerZone").on("dragenter",function(event){
event.preventDefault();
event.stopPropagation();
}).on("dragover",false)
.on("drop",function(event){
//What we need to check first is if the dropped task comes from the same page
var droppedTask = JSON.parse(event.originalEvent.dataTransfer.getData("application/json"));
var droppedTaskTabUUID = droppedTask["tabUUID"];
if(droppedTaskTabUUID != tabUUID){
alert("Task comes from another page and cannot be deleted");
return;
}else{
var droppedTaskId = droppedTask["id"];
var answer = confirm("Are you sure you want to delete this task?");
if(answer){
deleteTask(droppedTaskId);
}
}
});
});
In Google App Scripts (GAS), I want to be able to add and remove TextBox and TextArea elements to a FlexTable (that's being used as a form) and not worry about how many there are. I've named the text elements based on a counter to make this process easier.
So, is there a way to get the number of inputs (TextBox + TextArea) passed to e.parameter after the form is submitted?
Here's the relevant code from the FlexTable:
function doGet() {
var app = UiApp.createApplication();
var flex = app.createFlexTable().setId('myFlex');
var counter = 0;
var row_counter = 0;
...
var firstnameLabel = app.createLabel('Your FIRST Name');
var firstnameTextBox = app.createTextBox().setWidth(sm_width).setName('input' + counter).setText(data[counter]);
flex.setWidget(row_counter, 1, firstnameLabel);
flex.setWidget(row_counter, 2, firstnameTextBox);
row_counter++;
counter++;
var lastnameLabel = app.createLabel('Your LAST Name');
var lastnameTextBox = app.createTextBox().setWidth(sm_width).setName('input' + counter).setText(data[counter]);
flex.setWidget(row_counter, 1, lastnameLabel);
flex.setWidget(row_counter, 2, lastnameTextBox);
row_counter++;
counter++;
...
var submitButton = app.createButton('Submit Proposal');
flex.setWidget(row_counter, 2, submitButton);
var handler = app.createServerClickHandler('saveProposal');
handler.addCallbackElement(flex);
submitButton.addClickHandler(handler);
var scroll = app.createScrollPanel().setSize('100%', '100%');
scroll.add(flex);
app.add(scroll);
return app;
}
And here's the code for the ClickHandler (notice that I currently have 39 elements in my FlexTable):
function saveProposal(e){
var app = UiApp.getActiveApplication();
var userData = [];
var counter = 39;
for(var i = 0; i < counter; i++) {
var input_name = 'input' + i;
userData[i] = e.parameter[input_name];
}
So, is there a way to get the number of elements (in this case 39) without manually counting them and assigning this value to a variable?
I'm new at this stuff and I'd appreciate your help.
Cheers!
The simplest way is to add a hidden widget in your doGet() function that will hold the counter value like this :
var hidden = app.createHidden('counterValue',counter);// don't forget to add this widget as a callBackElement to your handler variable (handler.addCallBackElement(hidden))
then in the handler function simply use
var counter = Number(e.parameter.counterValue);// because the returned value is actually a string, as almost any other widget...
If you want to see this value while debugging you can replace it momentarily with a textBox...
You can search for arguments array based object.
function foo(x) {
console.log(arguments.length); // This will print 7.
}
foo(1,2,3,4,5,6,7) // Sending 7 parameters to function.
You could use a while loop.
var i = 0;
var userData = [];
while (e.parameter['input' + i] != undefined) {
userData[i] = e.parameter['input' + i];
i++;
};
OR:
var i = 0;
var userData = [];
var input_name = 'input0';
while (e.parameter[input_name] != undefined) {
userData[i] = e.parameter[input_name];
i++;
input_name = 'input' + i;
};
var ButtonFarmAtivada = new Array();
function X() {
var tableCol = dom.cn("td"); //cell 0
//create start checkbox button
ButtonFarmAtivada[index] = createInputButton("checkbox", index);
ButtonFarmAtivada[index].name = "buttonFarmAtivada_"+index;
ButtonFarmAtivada[index].checked = GM_getValue("farmAtivada_"+index, true);
FM_log(3,"checkboxFarm "+(index)+" = "+GM_getValue("farmAtivada_"+index));
ButtonFarmAtivada[index].addEventListener("click", function() {
rp_farmAtivada(index);
}, false);
tableCol.appendChild(ButtonFarmAtivada[i]);
tableRow.appendChild(tableCol); // add the cell
}
1) is it possible to create the button inside an array as I'm trying to do in that example? like an array of buttons?
2) I ask that because I will have to change this button later from another function, and I'm trying to do that like this (not working):
function rp_marcadesmarcaFarm(valor) {
var vListID = getAllVillageId().toString();
FM_log(4,"MarcaDesmarcaFarm + vListID="+vListID);
var attackList = vListID.split(",");
for (i = 0; i <= attackList.length; i++) {
FM_log(3, "Marca/desmarca = "+i+" "+buttonFarmAtivada[i].Checked);
ButtonFarmAtivada[i].Checked = valor;
};
};
For number 1) yes, you can.
function createInputButton(type, index) { // um, why the 'index' param?
// also, why is this function called 'createInputButton'
// if sometimes it returns a checkbox as opposed to a button?
var inputButton = document.createElement("input");
inputButton.type = type; // alternately you could use setAttribute like so:
// inputButton.setAttribute("type", type);
// it would be more XHTML-ish, ♪ if that's what you're into ♫
return inputButton;
}
I don't really understand part 2, sorry.