I am looking for some help.
I'd like to be able to add 2 variables and then set one of the variables to a higher digit.
function gain_points() {
var total_points = parseInt(0)
var points_per_click = parseInt(1)
var points_per_second = parseInt(0)}
I'd like to be able to add total_points and points_per_click together, and then for that to increase total_points.
Is this possible?
Having var total_points defined in the gain_points function it will be defined every time the function is called and assigned to the value of 0.
You may want to consider something like this:
var total_points = parseInt(0);
var points_per_click = parseInt(1);
var points_per_second = parseInt(0);
function gain_points() {
total_points = total_points + points_per_click;
}
This allows total_points to continue to increment every time that function is called.
You also don't need to use the parseInt(); The following would be just fine instead:
var total_points = 0;
var points_per_click = 1;
var points_per_second = 0;
total_points = total_points + points_per_click;
Is that what you are saying??
Sorry, can't comment, not enough rep...
Related
Suppose I need to declare a JavaScript variable based on a counter, how do I do so?
var pageNumber = 1;
var "text"+pageNumber;
The above code does not work.
In JavaScript (as i know) there are 2 ways by which you can create dynamic variables:
eval Function
window object
eval:
var pageNumber = 1;
eval("var text" + pageNumber + "=123;");
alert(text1);
window object:
var pageNumber = 1;
window["text" + pageNumber] = 123;
alert(window["text" + pageNumber]);
How would you then access said variable since you don't know its name? :) You're probably better off setting a parameter on an object, e.g.:
var obj = {};
obj['text' + pageNumber] = 1;
if you -really- want to do this:
eval('var text' + pageNumber + '=1');
I don't think you can do it sing JavaScript.I think you can use an array instead of this,
var textArray=new Array();
textArray[pageNumber]="something";
Assuming that the variable is in the global scope, you could do something like this:
var x = 1;
var x1 = "test"
console.log(window["x" + x]); //prints "test"
However, a better question might be why you want such behaviour.
You could also wrap your counter in an object:
var PageNumber = (function() {
var value = 0;
return {
getVal: function(){return value;},
incr: function(val){
value += val || 1;
this['text'+value]=true /*or some value*/;
return this;
}
};
})();
alert(PageNumber.incr().incr().text2); //=>true
alert(PageNumber['text'+PageNumber.getVal()]) /==> true
It can be done using this keyword in JS:
Eg:
var a = [1,2,3];
for(var i = 0; i < a.length; i++) {
this["var" + i] = i + 1;
}
then when you print:
var0 // 1
var1 // 2
var2 // 3
I recently needed something like this.
I have a list of variables like this:
var a = $('<div class="someHtml"></div>'),b = $('<div class="someHtml"></div>'),c = $('<div class="someHtml"></div>');
I needed to call them using another variable that held a string with the name of one of these variables like this:
var c = 'a'; // holds the name of the wanted content, but can also be 'b' or 'c'
$('someSelector').html(eval(c)) // this will just use the content of var c defined above
Just use eval to get the variable data.
I just did
I know a lot of the other answers work great, such as window["whatever"] = "x"; but I will still put my own answer here, just in case it helps.
My method is to use Object.assign:
let dict = {};
dict["test" + "x"] = "hello";
Object.assign(window, dict)
a little improvement over bungdito's answer, use the dynamic variable dynamically
var pageNumber = 1;
eval("var text" + pageNumber + "=123456;");
eval(`alert(text${pageNumber})`);
note: usage of eval is strongly discourgae
I have a Jquery function that helps with validation over 1 object. I need to expand it so that the function will run over 3 different objects. I am trying to define a function that takes a parameter(whichquote) to insert the appropriate object in the function. Here is my code. What I am doing wrong? I assume I do not have the selector correct as the code works if I put it in.
Original Function that works:
var depends = function() {
var selectorD = $("input[name^='lead[quote_diamonds_attributes]'], select[name^='lead[quote_diamonds_attributes]']");
var vals = '';
selectorD.not(':eq(0)').each(function () {
vals += $(this).val();
});
return vals.length > 0;
};
Function I am trying to create that allows me to use it on other objects. This currently does not work.
var depends = function(whichquote) {
var selectorD = $("input[name^='lead[+ whichquote +]'], select[name^='lead[+ whichquote +]']");**
var vals = '';
selectorD.not(':eq(0)').each(function () {
vals += $(this).val();
});
return vals.length > 0;
};
I think the problem is with my concating in the var selectorD but cannot seem to get the syntax correct.
Your selector isn't actually inputting whichquote because the string concatenation is incorrect.
Try
var selectorD = $("input[name^='lead[" + whichquote + "]'], select[name^='lead[" + whichquote +"]']");
Hi I want to loop through all defined variables in a jquery function for pushing corresponding variable name into an array. The code is given below
function pushallvariables()
{
var list = [];
var name = /^[A-Za-z\s.]+$/;
var general = /^[A-Za-z0-9\s.\-\/]{2,20}$/;
var email = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/;
var digit = /^[+]?[0-9\s]+$/;
list.push('name');
list.push('general');
list.push('email');
list.push('digit');
}
I want to modify this function into
function pushallvariables()
{
var list = [];
var name = /^[A-Za-z\s.]+$/;
var general = /^[A-Za-z0-9\s.\-\/]{2,20}$/;
var email = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/;
var digit = /^[+]?[0-9\s]+$/;
for each(variable as var)
{
list.push(var.name);
}
}
But the modified function is not correct. How can I write the function ?
The best and clear way to do that is:
var list = {};
list.name = /^[A-Za-z\s.]+$/;
list.general = /^[A-Za-z0-9\s.\-\/]{2,20}$/;
list.email = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/;
list.digit = /^[+]?[0-9\s]+$/;
without loops, etc
So I am working on a project of mine and I'd like some help.
I'd like javascript to be able to count in seconds, each second it'd add a preset amount of points.
var total_points = 0
var points_per_click = 1
var points_per_second = 0
function points_per_second() {
docuement.getElementById("current_points").innerHTML("Current Points: " + total_points);
//insert here?
}
I would also like the points_per_second to be able to add into the total_points var. Thanks!
docuement is spelt "document", .innerHTML is not a function call (set it like a variable) & variables and functions share the same namespace, i.e. don't set a variable points_per_second and then declare a function of the same name.
Once you have your syntax errors sorted, you were probably looking for setInterval.
var total_points = 0;
var points_per_click = 1;
var points_per_second = 2;
function update_display(){
var el = document.getElementById("current_points");
el.innerHTML = "Current Points: " + total_points;
//insert here? ... No
}
var ticker = setInterval(function(){
total_points += points_per_second;
// ... or whatever your intended logic
update_display();
}, 1000);
jsFiddle
I have a div with an ID "orangeButton" and each time you click on it it creates a new div. This works fine but... I want each newly created div to have an incremental number added to it's ID.
I am not sure how to do this.
Here is a fiddle of the code I have thus far with comments.
http://jsfiddle.net/taoist/yPrab/1/
Thank you
Javascript Code
var applicationArea = document.getElementById("applicationArea");
var orangeButton = document.getElementById("orangeButton");
orangeButton.onclick = function() {
var newDivThingy = document.createElement("div");
newDivThingy.id = 'newDivThingy'; // I want each newly created div to have a numeric value concatenated to it's ID. IE newDivThingy1 newDivThingy2 newDivThingy3
applicationArea.appendChild(newDivThingy);
};
Am I missing something, why not use a counter?
var counter = 0;
button.onclick = function(){
var newDivThingy = document.createElement("div");
newDivThingy.id = 'newDivThingy' + (++counter);
// continue your stuff here
}
Libraries like underscorejs provide a uniqueid function for this. Otherwise its easy to implement one.
myNamespace.uniqueId = (function () {
var counter = 0; // in closure
return function (prefix) {
counter++;
return (prefix || '') + '-' + counter;
};
}());
Usage.
newDiv.id = myNamespace.uniqueId('newDiv');
Simply use a integer and increment it as each element is added.
var applicationArea = document.getElementById("applicationArea"),
orangeButton = document.getElementById("orangeButton"),
counter = 1;
orangeButton.onclick = function() {
var newDivThingy = document.createElement("div");
newDivThingy.id = "newDivThingy" + counter++;
applicationArea.appendChild(newDivThingy);
}
I have no doubt you have solution and may have forgotten this post.
BUT, I wold like to show a solution that is a compact format.
Note the counter is set to (counter++) so it will start at 1.
var orangeButton = document.getElementById("orangeButton");
var counter = 0;
orangeButton.onclick = function() {
document.getElementById('applicationArea')
.appendChild(document.createElement('div'))
.setAttribute("id", 'newDivThingy' + counter++);
// I want each newly created div to have a
// numeric value concatenated to it's ID.
// IE newDivThingy1 newDivThingy2 newDivThingy3
};