unknown issue w/ JavaScript random number function - javascript

var randNum = function(){
var max = document.getElementById('max').value;
var min = document.getElementById('min').value;
var reps = document.getElementById('reps').value;
var i;
for (i=0; i<reps; i++){
var num = min + Math.floor(Math.random() * (max - min + 1)); //rand # 0-(max-1)
addTXT(num);
}
};
This function is supposed to take the numbers typed into the text boxes with the IDs 'min', 'max', and 'reps', and use them to come up with some random numbers. It doesn't write anything to the HTML document. The addTXT() function should write the number to a div, and I know it works because I've used it just fine before this. Any help would be appreciated. Also, I've been working with javascript less than a week, so I'm suspicious the problem is really obvious and I just don't see it.
var addTXT = function(newText){
var outputDiv=document.getElementById("console");
var oldText = outputDiv.innerHTML;
outputDiv.innerHTML = newText + oldText;
};

Parse the string values into integers with parseInt():
var max = parseInt(document.getElementById('max').value);
var min = parseInt(document.getElementById('min').value);
var reps = parseInt(document.getElementById('reps').value);
DEMO.

Where do you get the issue? If you unsure, try to put an alert in on certain spots in your code.
For example:
var randNum = function(){
alert('Function is triggered');
var max = document.getElementById('max').value;
var min = document.getElementById('min').value;
var reps = document.getElementById('reps').value;
var i;
for (i=0; i<reps; i++){
var num = min + Math.floor(Math.random() * (max - min + 1)); //rand # 0-(max-1)
alert(num);
addTXT(num);
}
};
If your addTxt function does not work, try the jQuery way
var randNum = function(){
alert('Function is triggered');
var max = document.getElementById('max').value;
var min = document.getElementById('min').value;
var reps = document.getElementById('reps').value;
var i;
for (i=0; i<reps; i++){
var num = min + Math.floor(Math.random() * (max - min + 1)); //rand # 0-(max-1)
alert(num);
$('#console').append(num);
}
};

Related

create a random integer unique in a given array

<div id='passarr'>1572 4528 3564 8921 4521</div>
I need to create a new random integer (4 digits), unique regarding the above content.
js
var content = $('#passarr').text();
var passarr = content.split(' ');
var pass = Math.floor(Math.random() * 9000) + 1000;
var i = 0;
while (i == 0) {
if (jQuery.inArray(pass, passarr) > -1) {
var pass = Math.floor(Math.random() * 9000) + 1000;
i = 1;
}
}
seems it works, but not sure this is the right and shortest way.
any suggestion?
Your code is the way to go. However, you can eliminate a few smaller mistakes ( an unneccessary i and non working code in < 0.00001%) :
var content = $('#passarr').text();
var passarr = content.split(' ');
do {
var pass = Math.floor(Math.random() * 9000) + 1000;
} while (jQuery.inArray(pass, passarr) > -1);
console.log(pass);

Randomize and show a given number if elements on pageload

I want to randomize elements on pageload - and just show 4 of them regardless on how many there are.
The closest I come is this:
$(document).ready(function() {
$(".itembox.newcenterbox").hide();
var elements = $(".itembox.newcenterbox");
var elementCount = elements.size();
var elementsToShow = 4;
var alreadyChoosen = ",";
var i = 0;
while (i < elementsToShow) {
var rand = Math.floor(Math.random() * elementCount);
if (alreadyChoosen.indexOf("," + rand + ",") < 0) {
alreadyChoosen += rand + ",";
elements.eq(rand).show();
++i;
}
}
});
It works for me on my local site - but it chrashes my live site.and I can't figure out why.
Is there a better way to do this?
Maybe your elementCount is less than elementsToShow? In this case, you will always get rand value between 0 and 3, and it will lead to an infinite loop.
Try the code below. Also I removed unnecessary loop iterations when you check the rand index.
$(document).ready(function() {
var elements = $(".itembox.newcenterbox");
var elementsToShow = 4;
var i = 0;
if(elements.length < elementsToShow) return;
for (i = 0; i < elementsToShow; i++) {
elements.splice(Math.floor(Math.random() * elements.length), 1);
}
elements.hide();
});

javascript getting user input to an array

hello im trying to get the minumum value of this array am i adding the user input to the array propperly.
var highestMark=0;
var gradeAwarded;
var StudentArr= [Student];
var markArr = [mark];
var Student = prompt("Enter Student Name: ", "Ross");
var mark = prompt("Enter Student Mark: ", 50);
var max;
function min (mark){
var min = Number.Max_Value;
for(var i = 0; i < mark.length; i++)
if(mark[i] < min)
min = mark[i];
}
return mark;
var smallest = min (mark);
document.write(smallest);
Ok, it's possible, but the prompt method return a string and you can lead with this string the way you want. For sample, if you user type some values separated by a specific char , (for sample) you could use the split method and get this array, for sample:
var values = prompt("Eter values: ", "");
var result = values.split(',');
but your code looks fine, just convert the mark[i] to number, to sample:
function min (mark){
var min = Number.Max_Value;
for(var i = 0; i < mark.length; i++)
if(number(mark[i]) < min)
min = number(mark[i]);
return mark;
}

JavaScript incrementing by 0.5 - how?

I have a problem incrementing a number by 0.5. I've used "+=" operator but instead of incrementing my number, this adds "0.5" value in the end of number. The example is this:
<script>
function setTempUp(){
var value = document.getElementById("targetTemp").firstChild.data;
var newvalue = value.replace("°","");
var num = new Number(newvalue);
var num = newvalue += 0.5;
var newtemp = newvalue + '°';
document.getElementById("targetTemp").innerHTML = newtemp;
var cover = document.getElementById('tempChange').clientHeight;
var coverInt = parseInt(cover, 10);
var coverNew = cover - 11;
document.getElementById('tempChange').setAttribute("style","height:" + coverNew + "px");
}
</script>
I'm also "attaching" "°" to my "newTemp", because I have temperature example. Is this a problem?
So, my number is 24 for example - when executed I get "240.5" :(
newvalue is a string. Use += on your num directly:
num += 0.5;
You are casting it to a number, but still call the string variable in the following code:
var num = new Number(newvalue);
var num = newvalue += 0.5;
var newtemp = newvalue + '°';
I think that what you meant to do was
var num = new Number(newvalue);
num = num += 0.5;
var newtemp = num + '°';
But whichever it is, you should keep a numeric variable out of the function, and increment that, instead of loading the temperature that you posted on the screen from the last run, and then do it again over and over.
newValue is a string - returned by value.replace("°","");
Instead of
var num = newvalue += 0.5;
Use
newValue = parseInt(newvalue, 10) + 0.5;
(Since you're not using num anywhere else, you don't need to assign it any result.)

Javascript Showing even numbers only

I've got this project where I have to generate random mathematics sums...
They are all 'divide by' sums, so I want to make all numbers even.
Can anyone help me with this? just ask if I'm not clear enough =)
<script>
$(function() {
var number = document.getElementById("breuken"),
i = 1;
for (; i <= 10; i++) {
var sRandom = Math.floor(Math.random()*10 + 1),
fRandom = Math.floor(sRandom + Math.random()*(20-sRandom )),
calc = Math.abs(fRandom / sRandom),
textInput = document.createElement('input'),
span = document.createElement('span'),
p = document.createElement('p');
textInput._calc = calc;
textInput.onchange = (function(p) {
return function(ev) {
var self = ev.target;
if (self.value == self._calc) {
p.style.color = 'green';
};
};
})(p);
span.innerHTML = fRandom + " : " + sRandom + " = ";
p.appendChild(span);
p.appendChild(textInput);
number.appendChild(p);
};
});
</script>
To get an even random number just:
halve you range and multiply by 2
var range = 100;
var number = Math.floor( Math.random() * range / 2 ) * 2;
or keep getting random numbers until you get an even one
var number;
do {
number = Math.floor(Math.random()*10 + 1)
} while( number % 2 == 1 );
Get a random integer over 1/2 the range and double it.

Categories

Resources