Using math.random in button to set a select option? - javascript

I'm trying to make a button that randomly sets a select option when clicked. I can't figure out what I am doing wrong though...
http://jsfiddle.net/GamerGorman20/nw8Ln6ha/25/
$('#rand').click(
function() {
randNum();
var num = "";
document.getElementById("mySelect").value.innerHTML = favWebComics[num];
});
var randNum = function() {
num = Math.round(Math.random() * 2) + 1;
return num;
};
The shown code is only a small part of the larger script housed in the linked jsfiddle.
I plan to add more selections later, but I want to get the code figured out before I spend time on those.
Worth mentioning, my understanding of this is very limited, so keeping the advice simple is GREATLY appreciated.

The relevant part of your code that you will need to change will look like this when complete (see the updated jsfiddle):
$('#rand').click(function() {
var $select = document.getElementById('mySelect'),
max = $select.getElementsByTagName('option').length - 1;
$select.selectedIndex = randNum(1, max);
myFunction();
});
var randNum = function(min, max) {
num = Math.floor(Math.random() * (max - min + 1)) + min;
return num;
};
var myFunction = function() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
document.getElementById("image").innerHTML = favWebComics[x][1];
document.getElementById("web").innerHTML = favWebComics[x][0];
document.getElementById("tags").innerHTML = "Tags: " + favWebComics[x][2];
};
I haven't changed the style or structure of your code, but just some of the basic properties.
The problem you have is with innerHTML. You cannot set innerHTML on an element's value.
Instead, what you can do is generate a random number and set the selectedIndex property of the select element to that random number.
Then, you'll call the function that displays the images and whatnot that you need.

You cannot change the select with innerHTML like this:
document.getElementById("mySelect").value.innerHTML = favWebComics[num];
You have to instead change the value, and apply the change like so
$("#mySelect").val("New text").change();
or
$("#mySelect").prop('selectedIndex', index).change();

Related

Looking to add a random number to html element? [duplicate]

Need help with Javascript to generate number in HTML. I'm close but can't get it to quite work. Help would be appreciated.
http://jsfiddle.net/xmPgR/251/
function getNumber() {
var minNumber = 0; // The minimum number you want
var maxNumber = 100; // The maximum number you want
var randomnumber = Math.floor(Math.random() * (maxNumber + 1) + minNumber); // Generates random number
$('#myNumber').html(randomnumber); // Sets content of <div> to number
return false; // Returns false just to tidy everything up
}
window.onload = getNumber; // Runs the function on click
document.getElementById("yourNumber").innerHTML = randomnumber;
<div id="myNumber"></div>
<p id="yourNumber">
</p>
Your onload works after the next statement, because it works asynchronously. And besides this, you use a randomnumber outside from it's scope, where it is not accessible.
So I suggest you to return the randomnumber from the function and use that function in the onload event handler. Inside that handler call your function, get the number and assign to your element's text.
And also if your getNumer's logic is to return the number, don't assign anything inside it, just return the number. It's responsibility is to return a random number. Pass the range to it, don't hard code: in another place you can need a random number in the different range. Other logic implement outside of that function.
function getRandomNumber(minRange, maxRange) {
return Math.floor(Math.random() * (maxRange + 1) + minRange);
}
window.onload = function() {
const rand = getRandomNumber(0, 100);
document.getElementById("yourNumber").innerHTML = rand;
$('#myNumber').html(rand);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myNumber"></div>
<p id="yourNumber"></p>
Here you go:
function getNumber() {
var minNumber = 0; // The minimum number you want
var maxNumber = 100; // The maximum number you want
var randomnumber = Math.floor(Math.random() * (maxNumber + 1) + minNumber); // Generates random number
document.getElementById("myNumber").innerHTML = randomnumber; // Sets content of <div> to number
return false; // Returns false just to tidy everything up
}
window.onload = getNumber; // Runs the function on click
<div id="myNumber"></div>
<p id="yourNumber">
</p>

The output from SetTimeout function is inconsistent

I am trying to create something like a Grid-Image-Box-Slider. Now what I am trying to achieve is that after a period of time (e.g 5 seconds) one of the images will be changed randomly. So, my script follows:
var currentImages = [1, 2];
(function imgCarousel() {
var min = 1;
var max = 6;
currentImgSlot = pickImageSlot();
var pickedImage = pickImage();
setTimeout(function () {
console.log("Image Slot: " + currentImgSlot + "<br> Image: " + pickedImage);
//var bgImgElem = document.getElementsByClassName('bg1');
var sheet = new CSSStyleSheet();
sheet.replaceSync('.bg' + currentImgSlot + ' {background-image: url("assets/img/' + pickedImage + '.jpg") !important}');
document.adoptedStyleSheets = [sheet];
return imgCarousel();
}, 5000)
})()
function pickImageSlot() {
var min = 1;
var max = 2;
var generatedImgSlot = generateRandomNumber(max, min);
if (generatedImgSlot == currentImgSlot) {
return pickImageSlot();
}
return generatedImgSlot;
}
function pickImage() {
var min = 1;
var max = 6;
var generatedImg = generateRandomNumber(max, min);
if (currentImages[currentImgSlot] == generatedImg) {
return pickImage();
}
currentImages[currentImgSlot] = generatedImg;
return generatedImg;
}
function generateRandomNumber(max, min) {
return Math.round(Math.random() * (max - min) + min)
}
So, here you can see that inside the imgCarousel() function I am using the setTimeout to change the background-image randomly after 5 seconds and then calling the same function again recursively. So, according to this code after each five seconds only one image should be changed. But, in reality, sometimes both of the images get changed at the same time. I don't know what is causing this issue.
Any help would be much appreciated. For your convenience I am sharing my code repo here:
Git Repo
Live Demo
It's a bit difficult to notice, but if you pay attention, in your live demo you'll actually see that each time they both change, one returns to the default. This is because you're actually just overriding the adoptedStyleSheets property with a new array consisting only of the latest override, so your other image will simultaneously return to the primary style sheet's image (the default).
There is no problem with the setTimeout, the issue is just that you need to be able to support both images being different from the default, instead of exactly one. You already keep both images in currentImages, so each time the timeout runs you can iterate over them and set each one's image in the new adopted style sheet.
Naively, something like this might work:
setTimeout(function () {
console.log("Image Slot: " + currentImgSlot + "<br> Image: " + pickedImage);
//var bgImgElem = document.getElementsByClassName('bg1');
var sheet = new CSSStyleSheet();
for(var i = 1; i < 2; i++) {
sheet.replaceSync('.bg' + i + ' {background-image: url("assets/img/' + currentImages[i]+ '.jpg") !important}');
}
document.adoptedStyleSheets = [sheet];
return imgCarousel();
}, 5000)
Your currentImages seems to be used with a random number between 1 and 2, but arrays are 0-based, so I'm not sure what your intended usage is there, but this should get you on the right track.

javascript random number looking for hasClass that doesn't exsist

To make this fairly simple my comments in the code say what I'm trying to accomplish. My code when executed seems to not continue to calculate until it finds an .wrap with an empty class, which is what I'm trying to do. Maybe someone can help me figure out how to extend the infinite checking to eventually find an open .wrap which the class has not been defined.
function computerMove(){
//returns number between 1-9
var rand = Math.floor((Math.random() * 9) + 1);
console.log(rand);
//checks for if .wrap has class of x and if it does it should get another number
var check = $(".board .wrap:nth-child("+rand+")").hasClass("x");
if(check){
console.log("checking")
var rand = Math.floor((Math.random() * 9) + 1);
//I believe this should work and repeat the function
computerMove();
}
else{
$(".board .wrap:nth-child("+rand+")").addClass("o");
}
No, don't use recursive function when you don't have to. Use loop.
function computerMove(){
var check;
var rand;
do {
//returns number between 1-9
rand = Math.floor((Math.random() * 9) + 1);
console.log(rand);
check = $(".board .wrap:nth-child("+rand+")").hasClass("x");
} while (check)
$(".board .wrap:nth-child("+rand+")").addClass("o");
}
Or it could be simpler to "smartly" use jQuery selector
// Find all elements that do not have x class
var items = $(".board .wrap:not(.x)")
// Get a random element
var target = items[Math.floor(Math.random()*items.length)];
// Add o class to the target
$(target).addClass('o')

Calculation results not displaying in totals table javascript

I'm trying to create a paycheck calculator, but when I enter the hourly rate and number of hours and hit calculate, all I'm getting is undefined in my totals table. Here is my javascript:
var $ = function (id) {
return document.getElementById(id);
}
function updateTotal () {
var rate;
var hours = parseFloat( $("numHours").value);
var regularHours;
var overtime;
var doubletime;
//begin determine hourly rate
function checkJob () {
if ($('job').value == 'job0') {
rate = 0;
}
if ($('job').value == 'job1') {
rate = 12;
}
if ($('job').value == 'job2') {
rate = 10;
}
if ($('job').value == 'job3') {
rate = 11;
}
}
//calculate hours breakdown
function checkHours () {
if (hours.value <= 40) {
regularHours = hours.value;
overtime = 0;
doubletime = 0;
}
if (hours.value < 60) {
regularHours = 40;
overtime = hours.value-40;
doubletime=0;
}
if (hours.value >=60) {
regularHours = 40;
overtime = 20;
doubletime = hours.value-60;
}
}
checkJob();
checkHours();
var salary = (regularHours * rate) + (overtime * (rate * 1.5)) + (doubletime * (rate * 2))
//display amounts
$('regularHours').innerHTML = regularHours;
$('overtime').innerHTML = overtime;
$('doubletime').innerHTML = doubletime;
$('salary').innerHTML = "$ " + salary;
}
I'm sure I'm missing something silly, but I've been staring at this code for days and can't figure out what I'm doing wrong. Thanks for looking!
EDIT
The offending code is this:
hours.value
The problem with it is that hours is already a number, and number does not have the method value available to it. Changing all instances of hours.value to hours will solve the problem and properly output a calculated result.
See this demo: http://jsfiddle.net/gLthv/
The problem is the way you are implementing your jquery selectors. You should either use document.getElementById() instead, or remember that to select an id, you need to prefix the id name with a #
$("#id")
That is only the first part of the problem though. The next part is that you are using jquery, but expecting dom elements. To unwrap the jquery object, you need to use [0] with it to be able to access the contained dom element.
$("#id")[0]
Once you make these changes, you should be able to see the reflected calculations. For example, $('job').value should really be $('#job')[0].value or if you prefer to stick with jquery's implementation then you can use $('#job').val() to get the value.
Similar to this you may also access jquery's implementation of innerHTML. That would change this: $('overtime').innerHTML = overtime to $('#overtime').html(overtime)

How to hide/show multiple square at different time

I'm still struggling with my simple javascript game. Here is my previous question: Simple javascript game, hide / show random square
Some square show and hide randomely for a few seconds and you have to click on them. I use RaphaelJS to draw the square and a few of JQuery ($.each() function)
I can't make the hide/show with the setInterval working for each square. The function made by Mishelle looks good but I get a "This is not a function" error.. I've test different stuff but it's not as obvious as I thought :/
window.onload = function() {
var paper = new Raphael(document.getElementById('canvas_container'), 500, 500);
// random function to for the x and y axis of the square
function random(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var rectanglemain = paper.rect(0, 0, 500, 500).attr({fill: "white",});
var win_click = 0; // set the var to count the click on the square
var recs = [];
for(var i = 0; i < 50; i++) {
var x = random(1,450);
var y = random(1,450);
var rec = paper.rect(x, y, 50, 50).attr({fill: 'blue'});
recs.push(rec); // add the square in an array
recs[i].click(function () {
//counting the clicks
win_click = win_click + 1;
})
function hideSquare() {recs[i].hide();}
hideSquare();
}
rectanglemain.click(function () {
alert('you click on ' + win_click + ' squares');
});
/* here is a function made by Mishelle on my previous question, unfortunately I can't make it work (this is not a function error).
function showBriefly (timeFromNow, duration) {
window.setTimeout(this.rec.show, timeFromNow);
window.setTimeout(this.rec.hide, timeFromNow + duration);
}
recs[2].showBriefly(1000, 3000); to test the function
*/
}
Thanks for the help :)
try
window.setTimeout(function(){this.rec.show();}, timeFromNow )
Just came across your problem, just in case you read this and you want to know what was the problem. this is undefined within the callback, thus you need to store which rectangle you were referring to in a variable (I've called it square), see my code:
showBriefly: function(timeFromNow, duration) {
square = this.box;
setTimeout(function(){square.show();}, timeFromNow )
setTimeout(function(){square.hide();}, timeFromNow + duration )
}
Cheers

Categories

Resources