So I try to create three values between 1 and 3 that are going to be different every time the page loads. It works perfectly when I open the page the first time, but whenever I try to reload or submit my form the page freeze and it is stuck loading. Any help is much appreciated!
function uniqueAnswerId(){
var rand = (Math.random() * 3.4);
while (Math.round(rand) == 0) {
var rand = (Math.random() * 3.4);
}
return (Math.round(rand));
}
var answerId1 = uniqueAnswerId();
function uniqueAnswerId2(){
var rand2 = (Math.random() * 3.4);
while (answerId1 == Math.round(rand2) || Math.round(rand2) == 0) {
var rand2 = (Math.random() * 3.4);
}
return (Math.round(rand2));
}
var answerId2 = uniqueAnswerId2();
function uniqueAnswerId3(){
var rand3 = (Math.random() * 3.4);
while (answerId1 == Math.round(rand3) || answerId2 == Math.round(rand3)){
while (Math.round(rand3) == 0){
var rand3 = (Math.random() * 3.4);
}
}
return (Math.round(rand3));
}
var answerId3 = uniqueAnswerId3();
console.log("AnswerIds: " + (answerId1) + ", " + (answerId2) + ", " + (answerId3))
your 3rd while loop should look like this, with another "||" in your condition instead of a whole new while loop.
function uniqueAnswerId3(answerId1, answerId2){
var rand3 = (Math.random() * 3.4);
while (answerId1 === Math.round(rand3) || answerId2 === Math.round(rand3) || Math.round(rand3)===0){
rand3 = (Math.random() * 3.4);
}
return (Math.round(rand3));
}
I believe you have an infinite loop. Here is the fiddle to fix your code.
Changes: Use '===' instead of '=='
Function Hoisting executes those functions before the variable declarations, which means referencing them inside the functions doesn't work. Added parameters to accept the arguments required.
https://jsfiddle.net/80xdmsjL/
function uniqueAnswerId(){
var rand = (Math.random() * 3.4);
while (Math.round(rand) === 0) {
rand = (Math.random() * 3.4);
}
return (Math.round(rand));
}
var answerId1 = uniqueAnswerId();
function uniqueAnswerId2(answerId1){
var rand2 = (Math.random() * 3.4);
while (answerId1 === Math.round(rand2) || Math.round(rand2) === 0) {
rand2 = (Math.random() * 3.4);
}
return (Math.round(rand2));
}
var answerId2 = uniqueAnswerId2(answerId1);
function uniqueAnswerId3(answerId1, answerId2){
var rand3 = (Math.random() * 3.4);
while (answerId1 === Math.round(rand3) || answerId2 === Math.round(rand3)){
while (Math.round(rand3) === 0){
rand3 = (Math.random() * 3.4);
}
}
return (Math.round(rand3));
}
var answerId3 = uniqueAnswerId3(answerId1, answerId2);
console.log("AnswerIds: " + (answerId1) + ", " + (answerId2) + ", " + (answerId3))
Take a look at this part of your code:
while (answerId1 === Math.round(rand3) || answerId2 === Math.round(rand3)){
while (Math.round(rand3) === 0){
rand3 = (Math.random() * 3.4);
}
}
Lets see what happen with the following values:
answerId1 = 1
answerId1 = 2
Math.round(rand3) = 1
in this case, you will have:
while (true){
while(false){
never_executed();
}
}
So it will loop until infinite in the outer 'while'.
To avoid this you could simply do what #Nicholas Bakolias says, add 'another "||" in your condition instead of a whole new while loop'
Related
I have problem with displaying true/false after submiting an answer to question.
I need to display true when answer is true e.g.( 14+1=15 true), but my code is always displaying false and never displays true.
Hope you will understand my code.
p.s. to display question press answer, in start it doesn't display question.
function myfunc() {
//randomizer + - * /
var symbol;
var s = Math.floor(Math.random() * 5);
if (s === 1) {
symbol = '+';
}
if (s === 2) {
symbol = '-';
}
if (s === 3) {
symbol = '*';
}
if (s === 4) {
symbol = '/';
}
//first num randomizer
var firstnum = Math.floor(Math.random() * 100);
//sec num randomizer
var secnum = Math.floor(Math.random() * 100);
document.getElementById('demo').innerHTML = firstnum + symbol + secnum;
//answer filter
var input = document.getElementById('input').value;
var testanswer;
if (s === 1) {
testanswer = firstnum + secnum;
}
if (s === 2) {
testanswer = firstnum - secnum;
}
if (s === 3) {
testanswer = firstnum * secnum;
}
if (s === 4) {
testanswer = firstnum / secnum;
}
//test answerer
if (testanswer === input) {
document.getElementById('atbilde').innerHTML = 'true';
}
else {
document.getElementById('atbilde').innerHTML = 'false';
}
}
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script type="application/javascript" src="test.js"></script>
</head>
<body>
<p id="demo"></p>
<input id="input" type="text">
<button id="mybt" type="button" onclick="myfunc()">submit</button><br>
<p id="atbilde"></p>
</body>
</html>
First of all, randomizing * 5 for 4 symbols is incorrect. Also, try to compare the answer to the actual numbers, not to the newly generated one.
var last = null;
myfunc();
function myfunc() {
//randomizer + - * /
var symbol;
var s = Math.floor(Math.random() * 4) + 1;
if (s === 1) {
symbol = '+';
}
if (s === 2) {
symbol = '-';
}
if (s === 3) {
symbol = '*';
}
if (s === 4) {
symbol = '/';
}
//first num randomizer
var firstnum = Math.floor(Math.random() * 10);
//sec num randomizer
var secnum = Math.floor(Math.random() * 10);
document.getElementById('demo').innerHTML = firstnum + symbol + secnum;
//answer filter
var input = document.getElementById('input').value;
var testanswer;
if (s === 1) {
testanswer = firstnum + secnum;
}
if (s === 2) {
testanswer = firstnum - secnum;
}
if (s === 3) {
testanswer = firstnum * secnum;
}
if (s === 4) {
testanswer = firstnum / secnum;
}
if (last != null) {
if (last == input && input != '') {
document.getElementById('atbilde').innerHTML = 'true';
} else {
document.getElementById('atbilde').innerHTML = 'false';
}
}
last = testanswer;
}
<form onsubmit="myfunc(); return false">
<p id="demo"></p>
<input id="input" type="text">
<button id="mybt" type="submit">submit</button><br>
<p id="atbilde"></p>
</form>
Need to separate generating questions from checking answers. I modified your code and added some comments:
HTML
<p id="demo"></p>
<input id="input" type="text">
<button id="mybt" type="button" onclick="checkAnswer()">submit</button><br>
<button type="button" onclick="showQuestion()">Show New Question</button><br>
<p id="atbilde"></p>
JavaScript:
var s, firstnum, secnum;
// first, show an initial question for a start
showQuestion();
// this method is used to show initial question and also to "Show New Question" when that button is pressed
function showQuestion(){
//randomizer + - * /
let symbol;
// changed formula to return 1, 2, 3, or 4. It was also returning 0 and 5 previously.
s = Math.floor(Math.random() * 4) + 1;
if (s === 1) {
symbol = '+';
}
if (s === 2) {
symbol = '-';
}
if (s === 3) {
symbol = '*';
}
if (s === 4) {
symbol = '/';
}
//first num randomizer
firstnum = Math.floor(Math.random() * 100);
//sec num randomizer
secnum = Math.floor(Math.random() * 100);
document.getElementById('demo').innerHTML = firstnum + symbol + secnum;
}
// when the user is ready and clicks submit, we check the answer using s, firstnum, and secnum
function checkAnswer() {
//answer filter
var input = document.getElementById('input').value;
var testanswer;
if (s === 1) {
testanswer = firstnum + secnum;
}
if (s === 2) {
testanswer = firstnum - secnum;
}
if (s === 3) {
testanswer = firstnum * secnum;
}
if (s === 4) {
testanswer = firstnum / secnum;
}
console.log('the answer is supposed to be ', testanswer, ' and the user submitted ', testanswer);
//test answer
// I changed === to == this way you can compare a string "100" to the number 100 and it will be true.
// Because "100" === 100 is false (it checks the type) and "100" == 100 is true (does not check the type.)
if (testanswer == input) {
document.getElementById('atbilde').innerHTML = 'true';
}
else {
document.getElementById('atbilde').innerHTML = 'false';
}
}
Can anyone help me figure out why my code of jQuery/javascript is just not working for the multiplication function? All the functions plus the multiplication function are working on my browser and android. The other functions except the multiplication one also work on IOS safari. I can't seem to see what's wrong with the multiplication function on IOS seeing as I've basically wrote all of these very similar to one another
function additionUncertainty() {
$(".button-addition").next(".Answer1").remove();
var Dx = $("input[name=Dx-add]").val();
var Dy = $("input[name=Dy-add]").val();
var sum = Math.sqrt((Dx * Dx) + (Dy * Dy));
if(sum == 0) return 0;
$(".button-addition").after('<p class = "Answer1"> Answer: ' +
sum.toFixed(4) + '</p>');
}
$("input[name=Dx-add], input[name=Dy-add]").keyup(function(event) {
if (event.keyCode === 13) {
$(".button-addition").click();
}
});
$(".button-addition").click(function() {
additionUncertainty();
});
// End Of Addition/Subtraction Uncertainty
function multiplicationUncertainty() {
$(".button-mult").next(".Answer").remove();
var Dx = $("input[name=Dx-mult]").val();
var Dy = $("input[name=Dy-mult]").val();
var x = $("input[name=x-mult").val();
var y = $("input[name=y-mult").val();
var sum = Math.sqrt((x*x*Dy*Dy) + (y*y*Dx*Dx));
if(sum == 0) return 0;
$(".button-mult").after('<p class = "Answer"> Answer: ' + sum.toFixed(4) + '</p>');
}
$("input[name=Dx-mult], input[name=Dy-mult], input[name=y-mult], input[name=x-mult]").keyup(function(event) {
if (event.keyCode === 13) {
$(".button-mult").click();
}
});
$(".button-mult").click(function() {
multiplicationUncertainty();
});
//End Of Multiplication Uncertainty
function divisionUncertainty() {
$(".button-div").next(".Answer").remove();
var Dx = $("input[name=Dx-div]").val();
var Dy = $("input[name=Dy-div]").val();
var x = $("input[name=x-div]").val();
var y = $("input[name=y-div]").val();
var sum = (Math.sqrt((x*x*Dy*Dy) + (y*y*Dx*Dx))) / (y*y);
if(sum == 0 || sum !== sum) return 0; //NaN is unequal to itself, sum !== sum is used to test this.
$(".button-div").after('<p class = "Answer"> Answer: ' + sum.toFixed(4) + '</p>');
}
$("input[name=Dx-div], input[name=Dy-div], input[name=y-div], input[name=x-div]").keyup(function(event) {
if (event.keyCode === 13) {
$(".button-div").click();
}
});
$(".button-div").click(function() {
divisionUncertainty();
});
//End of Division Uncertainty
function powerUncertainty() {
$(".button-pow").next(".Answer").remove();
var Dx = $("input[name=Dx-pow]").val();
var x = $("input[name=x-pow]").val();
var n = $("input[name=n-pow]").val();
var sum = (Math.pow(x, n-1))*Dx*n;
if(sum == 0 || sum !== sum) return 0;
$(".button-pow").after('<p class = "Answer"> Answer: ' + sum.toFixed(4) + '</p>');
}
$("input[name=Dx-pow], input[name=n-pow], input[name=x-div]").keyup(function(event) {
if (event.keyCode === 13) {
$(".button-pow").click();
}
});
$(".button-pow").click(function() {
powerUncertainty();
});
So, I'm creating a game in HTML/JS (Mostly Jquery).
I got an array of objects initialized at the beginning of the game (when user press P to play).Each object is a falling object (I know it's failing with a boolean named "working"), with "move" method setting a position going from 1 to 22. Each time it move, it show the current div with a number as ID (representing the position), and hide the previous div.
The problem is that, the game work perfectly with only one instance of the Object (so only one cell in the array), but when I try to put few other object, they don't move.
Here is the object constructor :
function flyers(){
this.pos = 0;
this.working = false;
this.jump = 0;
this.interval;
this.move = function(){
if (this.working == true){
if (this.pos == 22)
{
$("#perso21").hide();
this.pos = 0;
this.startWork();
}
checkSave();
if (this.jump == 0)
{ if ((this.pos == 5 && playerPos != 1) || (this.pos == 13 && playerPos != 2) || (this.pos == 19 && playerPos != 3))
{
this.die();
}
if ((this.pos == 4 && playerPos == 1) || (this.pos == 12 && playerPos == 2) || (this.pos == 18 && playerPos == 3))
this.jump = 1;
}
else
{
if (this.pos == 5 || this.pos == 13 || this.pos == 19)
{
score++;
this.jump = 0;
}
$(".score").html("" + score + "");
}
$("#perso" + (this.pos - 1) + "").hide();
$("#perso" + this.pos + "").show(); this.pos++;
}
else
clearInterval(this.interval);
};
this.startWork = function()
{
clearInterval(this.interval);
this.working = true;
this.interval = setInterval(this.move, 1000 - (score / 10 * 100));
}
this.die = function(){
this.working = false;
this.pos = 0;
this.jump = 0;
if (miss < 2)
{
miss++;
}
else
{
quitGame();
}
clearInterval(this.interval);
};
return this;}
And the array initialization :
flyerstab[0] = new flyers();
flyerstab[1] = new flyers();
flyerstab[2] = new flyers();
flyerstab[3] = new flyers();
flyerstab[0].startWork();
The spawner (only possible to have 4 objects falling at the same time)
spawn = setInterval(function()
{
var i;
for (var i = flyerstab.length - 1; i >= 0; i--) {
if (flyerstab[i].working == false)
{
flyerstab[i].startWork();
break;
}
else
console.log(i + " is working");
};
}, 5000 - (score / 10 * 100));
I tried to find why all the day, but I didn't manage to.. Am I constructing them bad ?
Inside of this.interval = setInterval(this.move, 1000 - (score / 10 * 100));, this.move is called with this as the global context. Instead, use
this.interval = setInterval(this.move.bind(this), 1000 - (score / 10 * 100));
I'm trying to write a Javascript calculation for an insurance sales form that I've designed. I'm very new to JS, and am having trouble getting the script to work. I would really appreciate if you could help point out what I'm missing! Thanks so much.
The script is meant to calculate an insurance premium based on two checkboxes (vars cb1 & cb2), a pair of radio buttons which indicate whether insured vehicles are for short or long haul trips (var haul), and the number of insured vehicles (vars trucks_num, cars_num, pvthire_num, buses_num, trailers_num).
At the end, I want the premium (var premium) to be displayed in the field "totalpremium".
I really appreciate your help!
Thank you :).
var cb1 = this.getField("cbexcellent");
var cb2 = this.getField("cbsatisfactory");
var haul = this.getField("haul");
var premium = this.getField("totalpremium");
var trucks_num = this.getField("over4.5t_num").value;
var cars_num = this.getField("cars_num").value;
var pvthire_num = this.getField("pvthire_num").value;
var buses_num = this.getField("buses_num").value;
var trailers_num = this.getField("trailers_num").value;
if((cb1 == "1") && (cb2 == "0") && (haul.valueAsString == "short")) {
var premium = (trucks_num.value * 150) + (cars_num.value * 100) + (pvthire_num.value * 250) + (buses_num.value * 150) + (trailers_num.value * 50);
}
if((cb1 == "0") && (cb2 == "1") && (haul.valueAsString == "short")) {
var premium = (trucks_num.value * 190) + (cars_num.value * 100) + (pvthire_num.value * 250) + (buses_num.value * 150) + (trailers_num.value * 50);
}
if((cb1 == "1") && (cb2 == "0") && (haul.valueAsString == "long")) {
var premium = (trucks_num.value * 190) + (cars_num.value * 100) + (pvthire_num.value * 250) + (buses_num.value * 150) + (trailers_num.value * 50);
}
if((cb1 == "0") && (cb2 = "1") && (haul.valueAsString == "long")) {
var premium = (trucks_num.value * 235) + (cars_num.value * 100) + (pvthire_num.value * 250) + (buses_num.value * 150) + (trailers_num.value * 50);
}
this.getField("totalpremium").value = premium.valueAsString
Check that the export values of your checkboxes match the values indicated as required in your if statements. By default these are set to Yes or No. If they don't match your script won't run right.
I've got a image slider on my website, it seems to work fine on IE, Firefox and Opera. But it doesn't work on Chrome and Safari. (Example: http://tommy-design.nl/ari/index.php)
<script type="text/javascript">
var data = [
["fotos/DSC_0055 (Large).JPG","Duitse herder","fotos/DSC_0055 (Large).JPG"],
["fotos/DSC_0154 (Large).JPG","Duitse herder","fotos/DSC_0154 (Large).JPG"],
["fotos/DSC_0194 (Large).JPG","Duitse herder","fotos/DSC_0194 (Large).JPG"],
["fotos/SSA41896 (Large).jpg","Duitse herder","fotos/SSA41896 (Large).jpg"],
["fotos/DSC_0143 (Large).JPG","Duitse herder","fotos/DSC_0143 (Large).JPG"]
]
imgPlaces = 4
imgWidth = 230
imgHeight = 122
imgSpacer = 0
dir = 0
newWindow = 1
moz = document.getElementById &&! document.all
step = 1
timer = ""
speed = 10
nextPic = 0
initPos = new Array()
nowDivPos = new Array()
function initHIS3()
{
for (var i = 0;i < imgPlaces+1;i++)
{
newImg=document.createElement("IMG")
newImg.setAttribute("id","pic_"+i)
newImg.setAttribute("src","")
newImg.style.position = "absolute"
newImg.style.width=imgWidth + "px"
newImg.style.height=imgHeight + "px"
newImg.style.border = 0
newImg.alt =""
newImg.i = i
newImg.onclick = function()
{
his3Win(data[this.i][2])
}
document.getElementById("display").appendChild(newImg)
}
containerEL = document.getElementById("container1")
displayArea = document.getElementById("display")
pic0 = document.getElementById("pic_0")
containerBorder = (document.compatMode == "CSS1Compat"?0:parseInt(containerEL.style.borderWidth) * 2)
containerWidth = (imgPlaces * imgWidth) + ((imgPlaces - 1) * imgSpacer)
containerEL.style.width=containerWidth + (!moz?containerBorder:"") + "px"
containerEL.style.height=imgHeight + (!moz?containerBorder:"") + "px"
displayArea.style.width = containerWidth+"px"
displayArea.style.clip = "rect(0," + (containerWidth+"px") + "," + (imgHeight+"px") + ",0)"
displayArea.onmouseover = function()
{
stopHIS3()
}
displayArea.onmouseout = function()
{
scrollHIS3()
}
imgPos = - pic0.width
for (var i = 0;i < imgPlaces+1;i++)
{
currentImage = document.getElementById("pic_"+i)
if (dir === 0)
{
imgPos += pic0.width + imgSpacer
}
initPos[i] = imgPos
if (dir === 0)
{
currentImage.style.left = initPos[i]+"px"
}
if (dir === 1)
{
document.getElementById("pic_"+[(imgPlaces-i)]).style.left = initPos[i]+"px"
imgPos += pic0.width + imgSpacer
}
if (nextPic == data.length)
{
nextPic = 0
}
currentImage.src = data[nextPic][0]
currentImage.alt = data[nextPic][1]
currentImage.i = nextPic
currentImage.onclick = function()
{
his3Win(data[this.i][2])
}
nextPic++
}
scrollHIS3()
}
timer = ""
function scrollHIS3()
{
clearTimeout(timer)
for (var i = 0;i < imgPlaces+1;i++)
{
currentImage = document.getElementById("pic_"+i)
nowDivPos[i] = parseInt(currentImage.style.left)
if (dir === 0)
{
nowDivPos[i] -= step
}
if (dir === 1)
{
nowDivPos[i] += step
}
if (dir === 0 && nowDivPos[i] <= -(pic0.width + imgSpacer) || dir == 1 && nowDivPos[i] > containerWidth)
{
if (dir === 0)
{
currentImage.style.left = containerWidth + imgSpacer + "px"
}
if (dir === 1)
{
currentImage.style.left = - pic0.width - (imgSpacer * 2) + "px"
}
if (nextPic > data.length-1)
{
nextPic = 0
}
currentImage.src=data[nextPic][0]
currentImage.alt=data[nextPic][1]
currentImage.i = nextPic
currentImage.onclick = function()
{
his3Win(data[this.i][2])
}
nextPic++
}
else
{
currentImage.style.left=nowDivPos[i] + "px"
}
}
timer = setTimeout("scrollHIS3()",speed)
}
function stopHIS3()
{
clearTimeout(timer)
}
function his3Win(loc)
{
if(loc === "")
{
return
}
if(newWindow === 0)
{
location = loc
}
else
{
newin = window.open(loc,'win1','left = 430,top = 340,width = 300 ,height = 300')
newin.focus()
}
}
</script>
I'm almost 100% sure that the problem lies in the array, but I can't seem to figure out what exactly the problem is..
Thanks in advance. :)
Try to use
position:relative;
and moving the first one from left to right / right to left(the others will follow accordingly as relative will tell em to follow the first image )
. i am pretty sure that that will start working on chrome then. as relative position tells it to use different positions. while opening your slider i found some bugs in chrome console : they all have the same left: thats getting changed together.