Need to pass local array to a function on click - javascript

I am writing a menu system and I need to call a function when the user clicks on a specific row. I am using new function to pass the div that called the function as well as the row the user clicked on. All well and good until I try to pass a local array to the function. If I do the following:
for (i=0;i<tmpdropnumber;i++){
var dv=document.getElementById(id+i);
dv.style.cursor="pointer";
dv.onmouseover = new Function('dropover'+"('" + id + "','" + i + "')");
dv.onmouseout = new Function('dropout'+"('" + id + "','" + i + "')");
dv.onclick = new Function('dropclick'+"('" + id + "','" + i + "','"+tmparray1+"','"+tmparray2+"')");
}
As you'd expect the arrays are passed as strings. I could rebuild the arrays in the function but that seems inelegant.
if I try the following:
for (i=0;i<tmpdropnumber;i++){
var dv=document.getElementById(id+i);
dv.style.cursor="pointer";
dv.onmouseover = new Function('dropover'+"('" + id + "','" + i + "')");
dv.onmouseout = new Function('dropout'+"('" + id + "','" + i + "')");
dv.onclick = new Function('dropclick'+"('" + id + "','" + i + "',"+tmparray1+","+tmparray2+")");
}
Trying to pass the arrays it crashes. Any ideas on how I can achieve this? I am using jquery in my code so wither a javascript or jquery solution would be fine.

Do not use new Function.
You are having problems because when the string is being built, the array is being turned into a string.
basic idea to get around the toString()
for (i=0;i<tmpdropnumber;i++){
var dv=document.getElementById(id+i);
dv.style.cursor="pointer";
(function(id, i){
dv.onmouseover = function(){ dropover(id,i); };
dv.onmouseout = function(){ dropout(id,i); };
dv.onclick = function(){ dropclick(id,i, tmparray1, tmparray2); };
})(id,i);
}
But in reality there is no need to pass in an object, id.
You can always use this to get the current row and there is rowIndex on the table. Heck you can have one event handler on the table and use handlers on the table/tbody to capture the bubbling and use target/srcElement.

Instead of
dv.onclick = new Function('dropclick'+"('" + id + "','" + i + "','"+tmparray1+"','"+tmparray2+"')");
try
dv.onclick = function() {
dropclick(id, i, tmparray1, tmparray2);
};
Edit
Wrap your declaration in a anonymous function:
(function(id, i) {
dv.onclick = function() {
dropclick(id, i, tmparray1, tmparray2);
};
} (id, i));

Related

If condicions inside email body

I'm building an app that will send an email with variables, but i only want to include certain things if a variable is true (checkbox)
So I think i need If statments inside the email.putExtra(Intent.EXTRA_TEXT,""); but I dont seem to figure out how. it would look something like this:
public void Email (){
Date today = Calendar.getInstance().getTime();
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY HH.mm");
String Time = formatter.format(today);
Intent email = new Intent(Intent.ACTION_SENDTO);
email.setData(Uri.parse("mailto:"));
email.putExtra(Intent.EXTRA_SUBJECT, "Audit" );
email.putExtra(Intent.EXTRA_TEXT, Time + "\n" + "Audit Results:"
if (MainActivity2.Send_A)=true{
MainActivity2.Ok_A1 + "\n" + MainActivity2.EditText1 + "\n" + MainActivity2.POA1
}
);
I know the code is completly wrong, but is it possible to do something like this?
Build up the string, than set that string to your function call.
var extraText = Time + "\n" + "Audit Results: ";
if (MainActivity2.Send_A === true){
extraText += MainActivity2.Ok_A1 + "\n" + MainActivity2.EditText1 + "\n" + MainActivity2.POA1;
}
email.putExtra(Intent.EXTRA_TEXT, extraText);

How to increment msg.payload[i] in node-red

We are working on an ubuntu server, where we have installed node-red. What we want is to take data from one table on our MySQL Database, and then move it to another table.
Our flow looks like this:
Our 'Select Tolerance' node contains:
msg.topic = "SELECT * FROM Tolerance";
return msg;
Simple code, which selects data from our database. If we connect a debug node like this:
We then see an output looking like this:
We want to pick all data, so we need to go through all objects in the array and make sure to take all values and send them over to our new database table. We're using the 'New Tolerance' node to do so, and 'New Tolerance' contains:
var i;
var secured = 1;
for (i = 0; i < msg.payload.length; i++) {
var time_start = msg.payload[i].time_start
var time_end = msg.payload[i].time_end
var temperatur_lpn = msg.payload[i].temperatur_lpn
var temperatur_rising = msg.payload[i].temperatur_rising
var temperatur_weather = msg.payload[i].temperatur_weather
var temp_compare_WL = msg.payload[i].temp_compare_WL
var temp_compare_WR = msg.payload[i].temp_compare_WR
var out = "INSERT INTO Sunrise_Tolerance (time_start, time_end, temperatur_lpn, temperatur_rising, temperatur_weather, temp_compare_WL, temp_compare_WR, secured)"
out = out + " VALUES ('" + time_start + "','" + time_end + "','" + temperatur_lpn + "','" + temperatur_rising + "','" + temperatur_weather + "','" + temp_compare_WL + "','" + temp_compare_WR + "','" + secured + "');"
msg.topic = out;
return msg;
}
The problem is that we only receive the first row of data (first object in the array) and not the rest. Can anyone figure out why we dont receive all data, but only the first?
The problem comes the fact you have a return statement inside the for loop.
That will exit the function the first time it reaches that point - so your loop never loops.
If you want to send multiple messages you should use node.send(msg); in your for loop. The only thing to watch out for is if you call node.send with the same object multiple times, as the message is passed by reference, you would get some odd side-effects. As you only care about msg.topic in this instance, you can afford to create a new message object each time.
So, instead of the return msg statement, you could do:
for (i ... ) {
var out = "INSERT ...";
...
node.send({topic: out});
}
// Return without any arguments so no further messages are sent.
return;

JavaScript sql result row, using a property that has parenthesis in its name

I am trying to do nested queries in order to insert into a table based apon an earlier select statement. However I am running into trouble because my first select statement selects and AVG() of a row. I have not been able to find a way to get the result row object that I have to select the property 'AVG(row)' instead of the trying to call .AVG() on something. The code is below and any help would be appreciated.
var sql1 = 'SELECT tropename, AVG(criticScore) FROM tropesWithScore where tropeName = '+ '\'' + trope + '\'';
//console.log(sql1)
con.query(sql1, function (err1, result1) {
if (err1) throw err1;
Object.keys(result1).forEach(function(key) {
var row2 = result1[key];
var trope2 = row.tropeName;
console.log(trope2)
var avgScore = row.AVG(criticScore)
console.log(avgScore)
sql = 'INSERT INTO TropesWithAverageScores (tropeName, criticScore) VALUES (' + trope2 + ',' + '\'' + avgScore + ')';
///console.log(sql)
con.query(sql, function (err, result) {
if (err) {}
});
});
});
Fixed it myself,
first, I was getting the attribute on row, not row2 object.
Secondly I simplified it by aliasing my first select state, so it now reads
SELECT tropename, AVG(criticScore) as avgCS FROM tropesWithScore where tropeName = '+ '\'' + trope + '\'';
Hope this helps someone else!

Extract string html with regex on interval

There is a public website with this in the source:
</div><script type="text/rocketscript">
function calculateIndexIncome() {
var khs = $('#t9').val();
var btcusd = $('#t9_1').val();
var btckhs = $('#t9_2').val();
var dayprofitperkhs = 0.00000018188885404454654
var arr = btcusd.split(' ');
btcusd = arr[0];
var totalinvestmentusd = ((khs * btckhs) * btcusd).toFixed(2);
var totalinvestmentbtc = (khs * btckhs).toFixed(8);
var dailyincomebtc = (khs * dayprofitperkhs).toFixed(8);
var dailyincomeusd = ((khs * dayprofitperkhs) * btcusd).toFixed(2);
var monthlyincomebtc = (dailyincomebtc * 31).toFixed(8);
var monthlyincomeusd = (dailyincomeusd * 31).toFixed(2);
var breakevendays = (totalinvestmentusd / dailyincomeusd).toFixed(0);
var monthlypercentage = ((100 / breakevendays) * 30).toFixed(2);
$('#tl').html('Total KHS: ' + khs + '<br/>Total Investment: ' + totalinvestmentbtc + ' BTC ($' + totalinvestmentusd + ' USD)<br/><br/>Daily Income: ' + dailyincomebtc + ' BTC ($' + dailyincomeusd + ' USD)<br/>Monthly Income: ' + monthlyincomebtc + ' BTC ($' + monthlyincomeusd + ' USD)<br/><br/>Break Even In: ' + breakevendays + ' Days.<br/><br/>Monthly Rate: ' + monthlypercentage + '%');
}
I need to be able to extract two values: btckhs and dayprofitperkhs.
if I look at page source, dayprofitperkhs is different everytime I refresh.
Edit:
Jimmy Chandra came up with this bookmarklet:
javascript:
setInterval(logging,60000);
w1 = window.open("https://scrypt.cc/index.php");
function logging(){
console.log (w1.$('#t9_2').val());
var re=/var\s*dayprofitperkhs\s*=\s*([0-9\.]+)\s*/gi;
var matches=re.exec(document.body.innerHTML);
console.log(RegExp.$1);
w1.location.href = 'https://scrypt.cc/index.php';
}
This works ALMOST perfectly. it gets the dayprofitperkhs, but only on the first interval.
After that, the value is no longer updated, although t9_2 IS updated...
Anyone?
I don't know where that site is, so I am just running this against this SO question, but the following bookmarklet is getting me what I want...
As I mentioned in the comment, I use Regular Expression against the document body inner html and I am looking for dayprofitperkhs and capturing the numbers and decimal separator on the right side of the equal sign. Also trying to compensate for any extra spaces in between (\s*). RegExp.$1 gave me the number that I am looking for.
javascript:(function(){var re=/var\s*dayprofitperkhs\s*=\s*([0-9\.]+)\s*/gi;var matches=re.exec(document.body.innerHTML);console.log(RegExp.$1);}());
So your final bookmarklet should be something like:
javascript:
setInterval(logging,60000);
w1 = window.open("siteurl.com");
function logging(){
console.log (w1.$('#t9_2').val());
var re=/var\s*dayprofitperkhs\s*=\s*([0-9\.]+)\s*/gi;
var matches=re.exec(w1.document.body.innerHTML);
console.log(RegExp.$1);
w1.location.href = 'siteurl.com';
}
The variables in question are local variables within the calculateIndexIncome() function, so no, you can't access them from outside that function.
The reason the first one "works" is because you're not referring to the variable, but rather the value: $('#t9_2').val(). This is a jquery selector which finds the element with the ID t9_2 and grabs its value.
You cannot visit it because its a local variable, it only exists in calculateIndexIncome() function.
By the way, you needn't open a new window to visit the variables. You can use chrome dev tools to directly modify the javascript to print the values, or set a breakpoint to debug the code.
Here is a tutorial for chrome dev tools: https://www.codeschool.com/courses/discover-devtools

Pass multiple parameters in view when using a string to call a JS function in MVC3

I am calling a function with one parameter "modalXPTO.HtmlFieldPrefix" sucessfuly like this:
modalXPTO.AdditionalJavaScriptCallback = "myFunction('" + modalXPTO.HtmlFieldPrefix + "')";
However, I would like to send more than one parameter, and I would expect this should work:
modalXPTO.AdditionalJavaScriptCallback = "myFunction('" + "{parentContainer:" + modalXPTO.ModalDivId + ", htmlFieldPrefix:" + modalXPTO.HtmlFieldPrefix + "}" + "')";
But it doesn't. Can anyone tell me what I am missing?
Here is the myFuntion declaration:
function myFunction(arg){
alert(arg.htmlFieldPrefix);
alert(arg.parentContainer);
}
I've fixed it.
modalXPTO.AdditionalJavaScriptCallback = "myFunction(" + "{parentContainer:'" + modalXPTO.ModalDivId + "', htmlFieldPrefix:'" + modalXPTO.HtmlFieldPrefix + "'}" + ")";
It is because of the misplaced "'". I wanted to pass an object with two parameters, but because of these characters I was passing a string instead.

Categories