Javascript to randomly add/subtract to a number every second - javascript

What I want my function to achieve for my javascript function is for every second to either randomly subtract or add (a random number) to a number held in a div.
Here's what I have so far.
It doesn't work, it seems to append the number to the end of the div value (100), and also it doesn't take into account that I want it to either randomly add or subtract (it just adds at the moment)
setInterval(function(){
random = (Math.floor((Math.random()*15)+1));
currentnumber = document.getElementById('number');
document.getElementById('number').innerHTML = currentnumber + random;
}, 1000);

parse the current value as an integer, and then do another math.random and use it to decide negative or positive. Lastly, you need to use the innerHTML of currentnumber, not the entire node. So something like this should work:
setInterval(function(){
random = (Math.floor((Math.random()*15)+1));
var plusOrMinus = Math.random() < 0.5 ? -1 : 1;
random = random * plusOrMinus;
currentnumber = document.getElementById('number');
document.getElementById('number').innerHTML = parseInt(currentnumber.innerHTML) + random;
}, 1000);
WORKING FIDDLE

.innerHTML returns you a string which you'll need to parse into an integer to perform the addition or subtraction. Have a look at a number of methods listed in the following SO question
How do I convert a string into an integer in JavaScript?

currentnumber is a DOM object, and you can't add that to a number.
var div = document.getElementById('number');
div.innerHTML = Number(div.innerHTML) + 3;
Notice you are getting the innerHTML of the div, converting that to a Number(), adding your random number to it, and THEN setting your div.innerHTML to your new value.
http://jsfiddle.net/9LqQG/1/

Maybe try something like this:
setInterval(function(){
random = (Math.floor((Math.random()*15)+1));
currentnumber = parseInt(document.getElementById('number').innerHTML);
document.getElementById('number').innerHTML = currentnumber + random;
}, 1000);
Your currentnumber variable needs to get the innerHTML of the element, then parse the string into an integer.
jsFiddle

Related

How to create a unique value each time when ever I run the java-script code?

I am using Math.random to create a unique value.
However , it looks like after some days , if i run the same script it produces the same value that created earlier.
Is there any way to create unique value every time when ever i run the script.
Below is my code for the random method.
var RandomNo = function (Min,Max){
return Math.floor(Math.random() * (Max - Min + 1)) + Min;
}
module.exports = RandomNo;
The best way to achieve a unique value is to use Date() as milliseconds. This increasing time representation will never repeat.
Do it this way:
var RamdomNo = new Date().getTime();
Done.
Edit
If you are bound to length restrictions, the solution above won't help you as repetition is predictable using an increasing number the shorter it gets.
Then I'd suggest the following approach:
// turn Integer into String. String length = 36
function dec2string (dec) {
return ('0' + dec.toString(36)).substr(-2);
}
// generate a 20 * 2 characters long random string
function generateId () {
var arr = new Uint8Array(20);
window.crypto.getRandomValues(arr);
// return 5 characters of this string starting from position 8.
// here one can increase the quality of randomness by varying
// the position (currently static 8) by another random number <= 35
return Array.from(arr, this.dec2string).join('').substr(8,5);
}
// Test
console.log(generateId());
This pair of methods generates a 40 characters long random string consisting of letters and digits. Then you pick a sequence of 5 consecutive characters off it.

(beginner) HTML + JS change variables with input value

Hello Stackoverflow people,
My question is how to change a variable I assigned with JavaScript using the value of an HTML input tag.
my progress:
<script type="text/javascript">
var x = 0;
document.write(x);
function addtox() {
var addx = document.getElementById("plusx").value;
x = x + addx;
}
</script>
<input id="plusx" type="number">
<input type="button" onclick="addtox()" value="add">
The result is that it literally adds the value of id="plusx" to the 0 that's already there. So if the input would be 50, it would return 050, and not 50. If I repeat the button it returns 05050 in stead of 100.
How can I fix this?
Also: how can I update text that is already writting to the screen? x is already written to the screenbefore the change and doesn't update after it is assigned a new value.
p.s
Sorry if I am a bit vague, not too familiar with coding questions like mine.
The value of an input element is a string type. You need to convert it to an integer:
x += parseInt(document.getElementById("plusx"), 10);
The return value from dom lookup is string. And so the result you are getting is string concatenation. Convert the return from dom lookup to integer using the parseInt () function. Then you should get the correct answer.
You can just put
X = "0" + addx;
This way you will always have the 0
- this will work if you just want to place a 0 In front.
if you want a more simple way of converting to integer just times your value by 1 will convert the strings to numbers.
So add in x = 0 * 1
And x= x + addx * 1
This will just give you your result without a 0 in front.
If you want 0 in front and number do
X = "0" + addx * 1;

How to select a random span from many spans javascript

I have a bunch of spans, they are set to display in-line block with a width and height of 60px, i want javascript to pick a random span from all of them and apply a color to it. I don't really even know where to begin with this. Any help would be appreciated.
For starters,
var elts = document.getElementsByTagName('span');
if using jQuery:
elts = $('span')
so now elts contains all the spans in the document.
The tricky part is selecting a random element within. We have to use Math.floor(Math.random() * elts.length) to select a random index. This is an earful, so the explanation:
Math.random() returns a random from [0,1).
elts.length is the length of the array. We multiply this by Math.random() to get a random array index from 0 to elts.length exclusive.
Math.floor() rounds down, so that we don't get an out of bounds exception.
Put it all together:
var myRandomSpan = elts[Math.floor(Math.random() * elts.length)]
and there you have it. You can do what you please with myRandomSpan.
You say you don't know where to begin. Well, with a little thought it becomes apparent:
1) Work out how to generate a random number in JS (easy Googling)
2) Work out how to pick out a random element form an array using point 1
3) Realise that a nodeset, e.g. as the result of getElementsByTagName or querySelectorAll is array-like (but not actually an array), and so we can pick out a particular element of it via square-bracket syntax, as with arrays. We can therefore apply point 2 to this nodeset.
So:
var
spans = document.querySelectorAll('span'),
span = spans[Math.floor(Math.random() * spans.length];
I have no idea if this will work - random code I pulled from various searches but in theory you could put all your spans into a array, count the length, generate random number bsaed on that length and access it via indecies:
var numSpans $("#container span").size();
var optionTexts = [];
// populat our span array
$("#container span").each(function() { optionTexts.push($(this).text()) });
var random = NumMath.floor(Math.random() * optionText.length);
var randomSpan = optionText[random];
You can give an integer id to your spans
<span id=1></span>
<span id=2></span>
...
<span id=100></span>
So, you just have to make a random number in between your ids. To generate a random integer between to numbers you can use this function:
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var randomID = getRandomInt(1, 100);
Then, with your random integer you can select the span like this:
document.getElementById(randomID)
If you are using jQuery you can change the background-color like this:
$("#" + randomID).css("background-color", {new_color})

Simple math in jquery

I am reading a select form value and multiplying it by 50 in jquery. I need to add a value of 1 to the qty that is returned by the select menu every time before multiplying by 50. How would I do that? The offending code looks like this.
$('#selectform').val() *50);
If I use
$('#selectform').val() +1 *50);
The result is not correct.
Parentheses should be used.
($('#selectform').val()*1 + 1) *50;
Your current expression is interpreted as:
var something = $('#selectform').val();
var another = 1 * 50;
var result = something + another
The *1 after .val() is used to convert the string value to a number. If it's omitted, the expression will be interpreted as:
var something = $('#selectform').val() + "1"; //String operation
var result = something * 50; // something is converted to a number, and
// multiplied by 50
Correct parentheses and use parseInt function -
(parseInt($('#selectform').val(),10) +1) *50;
The data from $('#selectform').val() is probably being treated as a string.
Use parseInt($('#selectform').val()) to convert it to an int before the multiply.
You should have a look at the operator precedence in JavaScript.
You need to force the addition to happen before the multiplication with parentheses:
bar myVal = ($("#selectform").val() + 1) * 50;

How do I add an integer value with javascript (jquery) to a value that's returning a string?

I have a simple html block like:
<span id="replies">8</span>
Using jquery I'm trying to add a 1 to the value (8).
var currentValue = $("#replies").text();
var newValue = currentValue + 1;
$("replies").text(newValue);
What's happening is it is appearing like:
81
then
811
not 9, which would be the correct answer. What am I doing wrong?
parseInt() will force it to be type integer, or will be NaN (not a number) if it cannot perform the conversion.
var currentValue = parseInt($("#replies").text(),10);
The second paramter (radix) makes sure it is parsed as a decimal number.
Parse int is the tool you should use here, but like any tool it should be used correctly. When using parseInt you should always use the radix parameter to ensure the correct base is used
var currentValue = parseInt($("#replies").text(),10);
The integer is being converted into a string rather than vice-versa. You want:
var newValue = parseInt(currentValue) + 1
parseInt didn't work for me in IE. So I simply used + on the variable you want as an integer.
var currentValue = $("#replies").text();
var newValue = +currentValue + 1;
$("replies").text(newValue);
In regards to the octal misinterpretation of .js - I just used this...
parseInt(parseFloat(nv))
and after testing with leading zeros, came back everytime with the correct representation.
hope this helps.
to increment by one you can do something like
var newValue = currentValue ++;
Simply, add a plus sign before the text value
var newValue = +currentValue + 1;
Your code should like this:
<span id="replies">8</span>
var currentValue = $("#replies").text();
var newValue = parseInt(parseFloat(currentValue)) + 1;
$("replies").text(newValue);
Hacks N Tricks
var month = new Date().getMonth();
var newmon = month + 1;
$('#month').html((newmon < 10 ? '0' : '') + newmon );
I simply fixed your month issue, getMonth array start from 0 to 11.
You can multiply the variable by 1 to force JavaScript to convert the variable to a number for you and then add it to your other value. This works because multiplication isn't overloaded as addition is. Some may say that this is less clear than parseInt, but it is a way to do it and it hasn't been mentioned yet.
You can use parseInt() method to convert string to integer in javascript
You just change the code like this
$("replies").text(parseInt($("replies").text(),10) + 1);

Categories