Same name for a string and a function - javascript

Right now I'm having a major brain fart. I have this function:
function uplodeVirus(){
console.log('working')
console.log('uplodeVirus')
var form = document.getElementsByTagName('form')[1]
console.log(form)
var select = form.children[0]
console.log(select)
for (x in select) {
var lN = select[x].innerHTML // var linkName
if (lN == "vspam 0.3 [OpenRelay-backdoor.vspam ] (0.003 Gb)"){
value = select[x].value
select[x].setAttribute("selected", "selected");
form.submit()
break
}
}
}
Don't worry its not a real Virus!!! This is a bot for a game called slave hack - for learning purposes
Anyways, when I call the function:
var ip = '2.2.2.2'
var uplodeVirus = 'http://www.slavehack.com/index2.php?page=internet&var2=' + ip + '&var3=files&aktie=upload'
var currentUrl = window.location.href
console.log(currentUrl)
console.log(uplodeVirus)
if (currentUrl == uplodeVirus) { //Yes, I made sure that currentUrl = uplodeVirus
uplodeVirus()
}
Nothing happens... but if I take the code out of the function and do this:
if (currentUrl == uplodeVirus){
console.log('working')
console.log('uplodeVirus')
var form = document.getElementsByTagName('form')[1]
console.log(form)
var select = form.children[0]
console.log(select)
for (x in select) {
var lN = select[x].innerHTML // var linkName
if (lN == "vspam 0.3 [OpenRelay-backdoor.vspam ] (0.003 Gb)"){
value = select[x].value
select[x].setAttribute("selected", "selected");
form.submit()
break
}
}
}
It works!!! Now, I could go with option B, but I really want to figure out what i did wrong.
Thanks in advance!

You are naming both a URL variable and a function with the same name: uplodeVirus
Since the variable is initialized to hold a string before you try to call the function, calling uplodeVirus() is the same as calling ("")(). It doesn't make any sense, because a string is not a function.
Try changing the name of one or the other.

Related

Passing values from an object inside a function

I have been working all day trying to pass the value of "returnData.salary" inside the "readData" function to
the object inside the "calculateTax" function which is suppose to take the salary value and calculate state and federal taxes. I am stumped, I can't find anything on the internet which provides a good example for me to work with. The examples are either way to simple or super complex. Any help would be appreciated.
I apologize in advance if I did not submit this question in the correct format. This is my first time asking for help on stackoverflow.
function readForm() {
var returnData = {};
returnData.name = $("#name").val();
returnData.lastName = $("#lastName").val();
returnData.age = $("#age").val();
returnData.gender = $("[name=gender]:checked").val();
returnData.salary = $("#salary").val();
returnData.isManager = $("#isManager").val();
returnData.myTextArea = $("#myTextArea").val();
$("#name2").text(returnData.name);
$("#lastName2").text(returnData.lastName);
$("#age2").text(returnData.age);
$("#gender2").text(returnData.gender);
$("#salary2").text(returnData.salary);
$("#myTextArea2").text(returnData.myTextArea);
if ($(isManager).is(':checked')) {
$("#isManager2").text("Yes");
}
else {
$("#isManager2").text("No");
}
//$("#employeeForm")[0].reset();
} //end of readForm function
function calculateTax() {
console.log("Button Works");
var calculateTax = {
state: function(num) {
num *= 0.09;
return num;
}
, federal: function(num) {
if (num > 10000) {
num *= 0.2;
return num;
}
else {
num * 0.1;
return num;
}
}
, exempt: true
};
}
//Invoke readForm function when the submit button is clicked.
$(document).ready(function () {
$("#btnSubmit").on("click", readForm);
$("#btnCalculate").on("click", calculateTax);
})
</script>
Well, simply put; you can't. Not like this anyway. Or, at least not pass the value to the function directly.
You are using global functions right now, which are not inside a class. If it was inside a class, you could instantiate the class and save it to this (which would be the class' instance). However, I'm assuming classes are a bit over complicated in this case. What you could do, is set variables globally so all functions can use them, like this;
//declare the global variable so it exists for every function
var returnData = {};
function readForm() {
//We do NOT redeclare the "var" again. It's global now.
returnData = {}; //Reset the global variable when this function is called
returnData.name = $("#name").val();
returnData.lastName = $("#lastName").val();
returnData.age = $("#age").val();
returnData.gender = $("[name=gender]:checked").val();
returnData.salary = $("#salary").val();
returnData.isManager = $("#isManager").val();
returnData.myTextArea = $("#myTextArea").val();
//Rest of your function
}
function calculateTax(){
console.log(returnData) //works here
}
Note that you do overwrite global variables, so it's best to reset them on every function call. You might get old data stuck in there, otherwise.

Pull specific field from nth index of Knockout observableArray of objects

I have a page that displays a list of file templates built using the following method.
var loadCustomTemplate = function () {
loadBaseTemplate();
var res = 0;
for (i = 0; i < self.GetSeam().length; i++) {
var a = self.count() + 1;
self.count(a);
res = self.GetSeam()[i].FileFormat.split("_");
if (res.length == 4) {
var ap = res[3].split('.');
self.append(ap[0]);
} else {
self.append("");
}
var obj = {
Code: ko.observable(self.code()),
Number: ko.observable(self.number()),
SeamReportPath: ko.observable(self.reportPath()),
FileFormat: ko.observable(self.append()),
SequenceNumber: ko.observable(a)
}
self.CustomTemplate.push(obj);
}
self.count(0);
};
The user is then allowed to edit the fields as needed. They can also add records or remove them as needed. The method to add a record is as follows.
self.addTemplate = function () {
var count = self.CustomTemplate().length + 1;
var obj = {
Code: ko.observable(self.code()),
Number: ko.observable(self.number()),
SeamReportPath: ko.observable(self.reportPath()),
FileFormat: ko.observable(""),
SequenceNumber: ko.observable(count)
}
self.CustomTemplate.push(obj)
};
Once those updates are made they can save the updated CustomTemplate. This uses ajax that is not important to this question. The save method calls a validation method that is supposed to check to make sure there are no duplicate FileFormat fields in the object array. This is what I have, but it is failing.
var validateTemplates = function() {
for (i = 0; i < self.CustomTemplate().length; i++) {
var checkVal = self.CustomTemplate()[i].FileFormat;
var checkSeq = self.CustomTemplate()[i].SequenceNumber;
for (j = 0; j < self.CustomTemplate().length; j++) {
if (checkSeq !== self.CustomTemplate()[j].SequenceNumber ){
if (checkVal+"" === self.CustomTemplate()[j].FileFormat) {
if (checkSeq == self.CustomTemplate()[j].SequenceNumber ){
return false;
}
}
}
}
return true;
};
The problem is that when checking self.CustomTemplate()[i].FileFormat and self.CustomTemplate()[i].SequenceNumber it isn't reflecting the data displaying on the page or the data being sent to the controller (MVC 4). If I put either of those in an alert it is showing a function. How do I access the data in those specific fields for comparison?
Thanks in advance.
If I put either of those in an alert it is showing a function.
That's because you're doing this kind of thing:
var checkVal = self.CustomTemplate()[i].FileFormat;
FileFormat is the result of ko.observable(...), which returns a function, so checkVal in fact does contain a function.
The solution is for all those cases to do this:
var checkVal = self.CustomTemplate()[i].FileFormat(); // Parentheses at the end!
The parentheses execute the observable function, and if you do so without parameters you "get" the value of that observable. (If you would pass in a value, it would "set" the observable to that value.)

window.onload is not fired

I am writing a chrome extension for practicing, which is basically remembers your password in a website the next time. However, I have a problem with running the code. window.onload, document.onload, none of them are fires my remember() function. Checked other answers, none of them could help. Checked if it gets overridden by actual code in the website, only body.onload is being overridden. Here is my code:
window.onload = remember;
var remember = function() {
var name = localStorage["name"];
var pw = localStorage["pw"];
if(pw != undefined && name != undefined)
{
document.sqrl.login_username.value = name;
document.sqrl.secretkey.value = pw;
};
document.sqrl.onsubmit = function() {
localStorage["name"] = document.sqrl.login_username.value;
localStorage["pw"] = document.sqrl.secretkey.value;
};
};
It executes the first two lines, but then does not enter inside the function, as I tested it with debugger in Chrome. What is missing in my code?
You are referencing to a variable before it is declared / visible in the scope. Do
var remember = function() {
...
...
};
window.onload = remember;
instead. Fiddle -> http://jsfiddle.net/9pcL3jz3/
You have several problems:
you use remember before defining it
your document.sqrl.login_username.value and document.sqrl.secretkey.value values depend on name and pw, name and pw depend on localStorage values, which in turn are set based on yourdocument.sqrlobjects. If you set document.sqrl.login_username.value and sqrl.secretkey.value somewhere else before the onsubmit is executed, then this is actually not a problem
you try to directly access "name" and "pw" from localStorage, I believe you cannot do that. Use the getItem and setItem functions instead
Suggested code:
var remember = function() {
var name = localStorage.getItem("name");
var pw = localStorage.getItem("pw");
if(pw != undefined && name != undefined)
{
document.sqrl.login_username.value = name;
document.sqrl.secretkey.value = pw;
};
document.sqrl.onsubmit = function() {
localStorage.setItem("name", document.sqrl.login_username.value);
localStorage.setItem("pw", document.sqrl.secretkey.value);
};
};
window.onload = remember;
EDIT:
I have read the comment of Xan and have tested the following code in my console:
localStorage["foo"] = "bar";
After reloading the page I have checked the value of localStorage["foo"] and it was "bar" indeed. Therefore, Xan was right and my third point is invalid indeed.
Try this?
window.onload = remember;
var remember = function() {
var name = localStorage.name;
var pw = localStorage.pw;
if(pw !== undefined && name !== undefined)
{
document.sqrl.login_username.value = name;
document.sqrl.secretkey.value = pw;
}
document.sqrl.onsubmit = function() {
localStorage.name = document.sqrl.login_username.value;
localStorage.pw = document.sqrl.secretkey.value;
};
};

RegExp Test with two variables : possible ?

I'm trying to use the Test() Method like I did here :
var namealbum = data.data[i].name;
var text = namealbum;
if (/les comics d/i.test(text) == false) {
//do nothing
} else {
var albumid = data.data[i].id;
$('body').append('<section id="album album'+j+'"><h2 id="album_title">'+text+'</h2><div id="images"></div></section>');
But I wonder if it's possible to use this method with two variables.
Kind of like this :
var comicname = photos.data[i].name;
var comicpicture= photos.data[i].source;
var comiclink = photos.data[i].link;
if (albumid.test(comiclink) == false){
}else {
$('#images').append('<img src="'+comicpicture+'"/>');
};
Actually, I want to test if there is the content of the variable albumid (which is the ID of an album) in the link of a photograph stored in the variable comiclink.
I hope you guys will understand my bad english.
Thank you though !
In this case there is no need to use a regex, You can String.indexOf() like
if (comiclink.toLowerCase().indexOf(albumid.toLowerCase()) > -1) {
If you still want to use a regex
//on page load
if (!RegExp.escape) {
RegExp.escape = function (value) {
return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&")
};
}
var regex = new RegExp(RegExp.escape(albumid), 'i');
if (regex.test(comiclink) == false) {} else {
$('#images').append('<img src="' + comicpicture + '"/>');
};

Get And Append ID in Javascript

Hey I tried this code for my project and it returns some bad results. getting the last Id does not work properly .
function regionDropDownChanged() {
var selectedRegionId = getRegionDropDown();
if (selectedRegionId !== null) {
var val = selectedRegionId[selectedRegionId.length - 1];
alert(val);
} else return;
$.get("/Common/JsonFunction/GetEnterprisesOfRegion", { regionId: val }, function (fields) {
fillDropDown(fields, getEnterpriseDropDown());
enableEnterpriseDropDown();
});
}
Also enableEnterpriseDropDown() Dropdown does not work after selecting IDs.
function enableEnterpriseDropDown() {
var enterpriseDropDown = getEnterpriseDropDown();
$(enterpriseDropDown).prop('disabled', false);
}
other methods that I use in my project
function getRegionDropDown() {
var dropDown = $("#RegionId").val();
return dropDown;
}
function getEnterpriseDropDown() {
var dropDown = $("#EnterpriseId");
return dropDown;
}
remember that I use Choosen Plugin.
Here you are using array of selectedRegionId but it is a value, as you have called getRegionDropDown() which returns a single value.
var selectedRegionId = getRegionDropDown();
So,
you may get undefined in alert in these lines
var val = selectedRegionId[selectedRegionId.length - 1];
alert(val);
If you create a Fiddle then it would be better to solve you problem.

Categories