How to make a javascript function with elementid like argument? - javascript

I have an DevExpress Mvc token extension, where the user will insert several items.
Using javascript I send the items to the controller, which is working fine.
My function look like this:
$(function() {
$("#btnSave").click(function () {
var name = window.ComboBox.GetValue();
var i;
var team = new Array();
var tokens = window.tokenBox.GetTokenCollection();
for (i = 0; i < tokens.length; i++) {
team.push(tokens[i]);
}
var s = new Array();
var ss = window.tokenBox2.GetTokenCollection();
for (i = 0; i < ss.length; i++) {
s.push(ss[i]);
}
var w = new Array();
var ww = window.tokenBox3.GetTokenCollection();
for (i = 0; i < ww.length; i++) {
w.push(ww[i]);
}
var o = new Array();
var oo = window.tokenBox4.GetTokenCollection();
for (i = 0; i < oo.length; i++) {
o.push(oo[i]);
}
var t = new Array();
var tt = window.tokenBox5.GetTokenCollection();
for (i = 0; i < tt.length; i++) {
t.push(tt[i]);
}
$.ajax({
type: "post",
url: '#Url.Action("Action","Controller")',
data: { name:name, team:team, s:s, o:o, w:w, t:t },
beforeSend: function () {
window.loadingPanel.Show();
},
success: function (response) {
$("#mainAjax").html(response);
window.loadingPanel.Hide();
}
});
});
});
I want to use a function, to get the items from token and put them in an array (not repetitive code like above), something like this:
function GetTokenItems(token) {
var list = new Array();
var el = document.getElementsById(token);
var tokens = el.GetTokenCollection();
for (var i = 0; i < tokens.length; i++) {
list.push(tokens[i]);
}
return list;
};
This function is not working, error says:
Uncaught TypeError: document.getElementsById is not a function
How can I pass the Id of the tokenBok like argument in a function, or/and what is wrong with my function?
**Edit:**
I made the correction document.getElementById and now I get the error:
Uncaught TypeError: el.GetTokenCollection is not a function

Should be document.getElementById(id):
Returns a reference to the element by its ID; the ID is a string which can be used to identify the element; it can be established using the id attribute in HTML, or from script.
document.getElementById(...)
// ^ without s

I found the answer of my issue, maybe will be helpfull for others!
For Devexpress mvc extensions is enough to use the name of the extension like argument, no need to look for him with document.getElementById, so my function is working like this:
function GetTokenItems(token) {
var list = new Array();
var tokens = token.GetTokenCollection();
for (var i = 0; i < tokens.length; i++) {
list.push(tokens[i]);
}
return list;
};
now I can call this function like this:
var team=GetTokenItems(tokenBox); and is working!!!

Related

Replace string in text area with the value of ajax response

I have an ajax function that returns a shorturl of an url from a textarea.
When I want to replace the shorturl by the actual url in the text area by using replace, the code not work. this is my implementation
Ajax function:
function checkUrl(text) {
var bit_url = "";
var url = text;
var username = "o_1i42ajamkg"; // bit.ly username
var key = "R_359b9c5990a7488ba5e2b0ed541db820";
return $.ajax({
url: "http://api.bit.ly/v3/shorten",
data: {
longUrl: url,
apiKey: key,
login: username
},
dataType: "jsonp",
async: false,
success: function(v) {
bit_url = v.data.url;
}
});
}
and a function that call the checkurl function is implemented as follow
$("#urlr").change(function() {
var text = $("#Pushtype_message").val();
var c = "";
var msgtext = "";
var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
var MsgStr = $("#Pushtype_message").val();
var Arr = text.split(" ");
urllist = new Array();
urluri = new Array();
i = 0;
for (var n = 0; n < Arr.length; n++) {
txtStr = Arr[n];
var urltest = urlRegex.test(txtStr);
if (urltest) {
urllist[i] = txtStr;
}
}
for (var i = 0; i < urllist.length; i++) {
// console.log(urllist[i].toString());
checkUrl(urllist[i]).done(function(result) {
var response = (result.data.url);
console.log(response);
MsgStr.replace(urllist[i], response);
console.log(MsgStr);
$("#Pushtype_message").val(MsgStr);
});
}
});
In my text area I put this text:
test utl function https://www.google.Fr test success
and I get in my console the following result
main.js http://bit.****
main.js test utl function https://www.google.Fr test success
As you see, the function return an urlshortner but the initial text still the same. My expected result is: test utl function http://bit.l**** test success, but this don't work.
When working with textarea you can simply replace their text.
$("#Pushtype_message").text(MsgStr);
You need the assign the new value to MsgStr
for(var i=0; i<urllist.length; i++){
// console.log(urllist[i].toString());
checkUrl(urllist[i]).done(function(result){
var response=(result.data.url);
console.log(response);
MsgStr = MsgStr.replace(urllist[i],response);
console.log(MsgStr);
$("#Pushtype_message").val(MsgStr);
});
}
i is defined outside your for loop and used inside it urllist[i]=txtStr; but its value is never assigned, it's alaways = 0:
i=0;
for (var n = 0; n < Arr.length; n++) {
txtStr = Arr[n];
var urltest=urlRegex.test(txtStr);
if(urltest)
{
urllist[i]=txtStr;
}
}
I found the solution about my problem,
I affect urllist[j] to a new variable text, because in the checklist function urllist[j] return an undefined value.
var j=0;
for(j; j<urllist.length; j++){
var text=urllist[j];
checkUrl(urllist[j]).done(function(result){
var response=result.data.url;
console.log(urllist[j]);
MsgStr1 = MsgStr.replace(text,response);
console.log(MsgStr1);
$("#Pushtype_message").val(MsgStr1);
});
}
});

Callback is undefined and other stories

I got the following script, which is not working propperly. I know about getJSON's async nature, so I tried to build a callback function (jsonConsoleLog), which is supposed to be executed before getJSON get asigned to var (myJson = json;). After running debug in Chrome, I got two things out: A) debug is highlighting jsonConsoleLogcalls inside getJSON function as undefined.
B) Console is throwing TypeError: Cannot read property '0' of null for var friends = myJSON[0].friends;, which means the whole function doesn't work.
I'm in battle with it since saturday and I really don't know what to do. There's clearly something up with my callback function, but shoot me if I know what. Help?
var myJSON = null;
var main = document.getElementsByClassName('main');
var sec = document.getElementsByClassName('sec');
function getJSON(jsonConsoleLog){
$.getJSON('http://www.json-generator.com/api/json/get/cpldILZRfm? indent=2', function(json){
if (json != null){
console.log('Load Successfull!');
};
if (jsonConsoleLog){
jsonConsoleLog(json[0].friends);
}
myJSON = json;
});
};
function jsonConsoleLog(json) {
for (var i = 0; i < json.length; i++) {
console.log('friend: ' + friends[i]);
};
};
getJSON();
var friends = myJSON[0].friends;
function myFn1(){
for(var i = 0; i < friends.length; i++) {
main[i].innerHTML = friends[i].id;
};
};
function myFn2(){
for(var i = 0; i < friends.length; i++) {
main_div[i].innerHTML = friends[i].name;
};
};
main.innerHTML = myFn1();
sec.innerHTML = myFn2();
The first problem is because your function getJSON is expecting one formal argument, which you've called jsonConsoleLog. But you are not passing any arguments to getJSON. This means that inside getJSON the formal parameter, jsonConsoleLog, will indeed be undefined. Note that because you've named the formal parameter jsonConsoleLog, which is the same name as the function you're hoping to call, inside getJSON you won't have access to the function. What you need to do is pass the function as the parameter:
getJSON(jsonConsoleLog);
The second problem is I think to do with the json variable - it doesn't have a property 0 (i.e. the error is occurring when you try to treat it as an array and access element 0), which suggets that json is coming back empty, or is not an array.
you're calling getJSON without the callback parameter - therefore, the local variable jsonConsoleLog is undefined in getJSON
snip ...
function blah(json) { // changed name to avoid confusion in the answer - you can keep the name you had
for (var i = 0; i < json.length; i++) {
console.log('friend: ' + friends[i]);
};
};
getJSON(blah); // change made here (used the function name blah as changed above
var friends = myJSON[0].friends;
function myFn1(){
for(var i = 0; i < friends.length; i++) {
main[i].innerHTML = friends[i].id;
};
};
snip...
The issue with
var friends = myJSON[0].friends;
is duplicated here many many times ... $.getJSON is asynchronous and you are trying to use it synchronously
i.e. when you assign var friends = myJSON[0].friends; myJson hasn't been assigned in $.getjson ... in fact, $.getjson hasn't even BEGUN to run
here's all your code reorganised and rewritten to hopefully work
var main = document.getElementsByClassName('main');
var sec = document.getElementsByClassName('sec');
function getJSON(callback) {
$.getJSON('http://www.json-generator.com/api/json/get/cpldILZRfm? indent=2', function(json) {
if (json != null) {
console.log('Load Successfull!');
};
if (callback) {
callback(json);
}
});
};
function doThings(json) {
var friends = json[0].friends;
for (var i = 0; i < friends.length; i++) {
console.log('friend: ' + friends[i]);
};
function myFn1() {
for (var i = 0; i < friends.length; i++) {
main[i].innerHTML = friends[i].id;
};
};
function myFn2() {
for (var i = 0; i < friends.length; i++) {
main_div[i].innerHTML = friends[i].name;
};
};
main.innerHTML = myFn1();
sec.innerHTML = myFn2();
}
getJSON(doThings);
Correct, fully working code (basically the same as accepted, correct answer but stylistycally bit different)
var main = document.getElementsByClassName('main');
var sec = document.getElementsByClassName('sec');
var friends = null;
function getJSON(jsonConsoleLog){
$.getJSON('http://www.json-generator.com/api/json/get/cpldILZRfm?indent=2', function(json){
if (json != null){
console.log('Load Successfull!');
};
if (jsonConsoleLog){
jsonConsoleLog(json[0].friends);
}
});
};
function jsonConsoleLog(json) {
for (var i = 0; i < json.length; i++) {
console.log('friend: ' + json[i]);
};
friends = json;
myFn1();
myFn2();
};
function myFn1(){
for(var i = 0; i < friends.length; i++) {
main[i].innerHTML = friends[i].id;
};
};
function myFn2(){
for(var i = 0; i < friends.length; i++) {
main[i].innerHTML += friends[i].name;
};
};
getJSON(jsonConsoleLog);

Accessing Array inside jquery function 'undefined'

I have a 2 Dimension Array.
I am trying to access it inside my Mousemove jquery function INSIDE my Canvas function. When i try so, i get the following error :
Uncaught TypeError: Cannot read property '0' of undefined
function Canvas(_canvas) {
this.pixels = new Array();
for (var i = 0; i<this.canvas.width; i++) {
var row = new Array();
for (var j=0; j<this.canvas.height; j++) {
row.push(i*j);
}
this.pixels.push(row);
}
$("#" + _canvas).mousemove(function(e){
var offset = $(this).offset();
console.log(this.pixels[parseInt(e.clientX-offset.left)][parseInt(e.pageY-offset.top)]);
});
};
My array is accessible properly from any other function inside my Canvas function, except for the Jquery ones. Any thoughts on that ?
Thanks
alias this into that to avoid ambiguity in the event handler between the instance and the event-raising element:
function Canvas(_canvas) {
var that=this;
this.pixels = new Array();
for (var i = 0; i<this.canvas.width; i++) {
var row = new Array();
for (var j=0; j<this.canvas.height; j++) {
row.push(i*j);
}
this.pixels.push(row);
}
$("#" + _canvas).mousemove(function(e){
var offset = $(this).offset();
console.log(that.pixels[parseInt(e.clientX-offset.left)][parseInt(e.pageY-offset.top)]);
});
};

How to change array variable name dynamically

I am working for some common method in javascript, for that i have to call array dynamically.
var ddlText, ddlValue, ddl, lblMesg, ddlTextCacheList_Designation, ddlValueCacheList_Designation, ddlTextCacheList_Scale, ddlValueCacheList_Scale;
function cacheDes() {
var listDes = document.getElementById("<%=List_Designation.ClientID %>");
ddlTextCacheList_Designation = new Array();
ddlValueCacheList_Designation = new Array();
for (var i = 0; i < listDes.options.length; i++) {
ddlTextCacheList_Designation[ddlTextCacheList_Designation.length] = listDes.options[i].text;
ddlValueCacheList_Designation[ddlValueCacheList_Designation.length] = listDes.options[i].value;
}
}
function cacheScale() {
var listScale = document.getElementById("<%=List_Scale.ClientID %>");
ddlTextCacheList_Scale = new Array();
ddlValueCacheList_Scale = new Array();
for (var i = 0; i < listScale.options.length; i++) {
ddlTextCacheList_Scale[ddlTextCacheList_Scale.length] = listScale.options[i].text;
ddlValueCacheList_Scale[ddlValueCacheList_Scale.length] = listScale.options[i].value;
}
}
window.onload = function () {
cacheDes();
cacheScale();
};
I want to call array ddlTextCacheList_Scale or ddlTextCacheList_Designation for same method as we know 'ddlTextCacheList_' is common only we need to put 'Scale' or 'Designation' dynamicaaly by passing parameter.
Add:
I get some errors:
I suggest you to improve your cache to store all in one object to easy access...
For example:
var CacheStorage = {};
function cache(key, list) {
CacheStorage[key] = list.map(function(option){
return {text: option.text, value: option.value};
});
}
function del(key, index) {
CacheStorage[key].splice(index, 1);
}
cache('Scale', getElementByID('...').options);
cache('Designation', getElementByID('...').options);
del('Designation', 0);

nested javascript queries in parse

I have the code below. Basically I have 3 nested parse queries. One is getting a number of "followers" and for each follower I am getting a number of "ideas" and for each idea I would like to get that idea creator's name (a user in the user table).
The first two nested queries work but then when i try to get the name of the user (the creator of the idea), that last nested query DOES NOT execute in order. That query is skipped, and then it is executed later in the code. Why is this happening please?
var iMax = 20;
var jMax = 10;
var IdeaList = new Array();
var IdeaListCounter = 0;
var myuser = Parse.User.current();
var Followers = new Parse.Query("Followers");
Followers.equalTo("Source_User",{__type: "Pointer",className: "_User",objectId: myuser.id});
Followers.find({
success: function(results) {
for (var i = 0; i < results.length; i++) {
var object = results[i];
var Ideas = new Parse.Query("Ideas");
Ideas.equalTo("objectId_User", {__type: "Pointer",className: "_User",objectId: object.get('Destination_User').id});
Ideas.find({
success: function(results2) {
for (i=0;i<iMax;i++) {
IdeaList[i]=new Array();
for (j=0;j<jMax;j++) {
IdeaList[i][j]=0;
}
}
for (var j = 0; j < results2.length; j++) {
var object2 = results2[j];
var ideausername2 = "";
IdeaListCounter++;
var ideausername = new Parse.Query("User");
ideausername.equalTo("objectId",object2.get('objectId_User').id);
ideausername.first({
success: function(ideausernameresult) {
ideausername2 = ideausernameresult.get("name");
}
});
IdeaList[IdeaListCounter,0] = object2.get('objectId_User').id + " " + ideausername2; //sourceuser
IdeaList[IdeaListCounter,1] = object2.get('IdeaText'); //text
IdeaList[IdeaListCounter,2] = object2.get('IdeaImage'); //image
IdeaList[IdeaListCounter,3] = object2.get('IdeaLikes'); //likes
IdeaList[IdeaListCounter,4] = object2.get('IdeaReport'); //reports
Your nested query is asynchronous.
Check out the answer at the following for guidance:
Nested queries using javascript in cloud code (Parse.com)

Categories