So I have a button with onclick that runs 3 functions and each function is to display a random symbol. So when I press the button, it should output 3 random symbols, but only one symbol it outputted when I click the button.
<!DOCTYPE html>
<html>
<head>
<title>MyFirstJavaScript</title>
</head>
<body>
<script>
function slots1()
{
var slot1 = Math.floor(Math.random()*4);
if (slot1 == 0) {
document.getElementById('value').innerHTML = "\u2663";
}
if (slot1 == 1) {
document.getElementById('value').innerHTML = "\u2665";
}
if (slot1 == 2) {
document.getElementById('value').innerHTML = "\u2666";
}
if (slot1 == 3) {
document.getElementById('value').innerHTML = "\u2660";
}
}
function slots2()
{
var slot2 = Math.floor(Math.random()*4);
if (slot2 == 0) {
document.getElementById('value').innerHTML = "\u2663";
}
if (slot2 == 1) {
document.getElementById('value').innerHTML = "\u2665";
}
if (slot2 == 2) {
document.getElementById('value').innerHTML = "\u2666";
}
if (slot2 == 3) {
document.getElementById('value').innerHTML = "\u2660";
}
}
function slots3()
{
var slot3 = Math.floor(Math.random()*4);
if (slot3 == 0) {
document.getElementById('value').innerHTML = "\u2663";
}
if (slot3 == 1) {
document.getElementById('value').innerHTML = "\u2665";
}
if (slot3 == 2) {
document.getElementById('value').innerHTML = "\u2666";
}
if (slot3 == 3) {
document.getElementById('value').innerHTML = "\u2660";
}
}
</script>
<button type="button" value="Spin" name="SPIN" onClick="slots1();slots2();slots3();">Spin</button>
<span id="value"></span>
</body>
</html>
Each function basically overrides the value that's changed by the previous one, so the only value you see is the result of slots3(). This following line is common to all your functions and it's your override:
document.getElementById('value').innerHTML = //some value;
Related
I'm making a calculator like the Windows calculator, and have completed it, the only thing I cannot do is make the CE button usable. I want the CE button to delete the last equation you entered, eg. if you enter like 78-89*90, it will delete the *90 only.
Here is the javascript code I have:
var display = document.getElementById("screen");
var buttons = document.getElementsByClassName("button");
Array.prototype.forEach.call(buttons, function(button) {
button.addEventListener("click", function() {
if (button.textContent != "=" &&
button.textContent != "C" &&
button.textContent != "x" &&
button.textContent != "÷" &&
button.textContent != "√" &&
button.textContent != "x ²" &&
button.textContent != "%" &&
button.textContent != "⌫" &&
button.textContent != "1/x" &&
button.textContent != "CE" &&
button.textContent != "±") {
display.value += button.textContent;
} else if (button.textContent === "=") {
equals();
} else if (button.textContent === "C") {
clear();
} else if (button.textContent === "x") {
multiply();
} else if (button.textContent === "÷") {
divide();
} else if (button.textContent === "±") {
plusMinus();
} else if (button.textContent === "⌫") {
backspace();
} else if (button.textContent === "%") {
percent();
} else if (button.textContent === "x ²") {
square();
} else if (button.textContent === "√") {
squareRoot();
} else if (button.textContent === "1/x") {
divide1();
} else if (button.textContent === "CE") {
clearone();
}
});
});
function syntaxError() {
if (eval(display.value) == SyntaxError || eval(display.value) == ReferenceError || eval(display.value) == TypeError) {
display.value == "Syntax Error";
}
}
function equals() {
if ((display.value).indexOf("^") > -1) {
var base = (display.value).slice(0, (display.value).indexOf("^"));
var exponent = (display.value).slice((display.value).indexOf("^") + 1);
display.value = eval("Math.pow(" + base + "," + exponent + ")");
} else {
display.value = eval(display.value)
checkLength()
syntaxError()
}
}
function clear() {
display.value = "";
}
function backspace() {
display.value = display.value.substring(0, display.value.length - 1);
}
function multiply() {
display.value += "*";
}
function divide() {
display.value += "/";
}
function plusMinus() {
if (display.value.charAt(0) === "-") {
display.value = display.value.slice(1);
} else {
display.value = "-" + display.value;
}
}
function square() {
display.value = eval(display.value * display.value);
}
function squareRoot() {
display.value = Math.sqrt(display.value);
}
function percent() {
display.value = display.value / 100;
}
function divide1() {
display.value = 1 / display.value;
}
I need to make a function called clearone that as said before, cleans the last equation you entered.
Thanks in advance.
Just split the values and check one by one and remove the value if it's a number and break the loop when is not a number.
function clearone(){
let v = '78-89*90'.split('');
let ar = [0,1,2,3,4,5,6,7,8,9];
for(a of v){
let index = ar.indexOf(parseInt(a));
if(index == -1){
v.pop();
v= v.join("");
console.log(v);
break;
}else{
v.pop();
}
}
}
clearone();
I'm a beginner to JavaScript. Can someone help me in this regard?
In the below code the logic for submit button doesn't work. _btn.addEventListener. Only the if part is getting executed, some issue with the else part condition. If the "if" condition gets satisfied then the alert is getting executed and not the conditions in else part even if the date and image is clicked.
<p align=center>
<input type="submit" value="submit" id="button">
</p>
<script type="text/javascript">
let _img = document.getElementById("img");
let _img1 = document.getElementById("img1");
let _img2 = document.getElementById("img2");
let _picker = document.getElementById("picker");
let _btn = document.getElementById("button");
let isImgClicked = false;
let isDatePicked = false;
/*let ImgClicked = '_img';
let ImgClicked1 = '_img1';
let ImgClicked2 = '_img2';
let DatePicked = '2019';
let DatePicked1 = '2020';*/
_img.addEventListener("click", function(){
isImgClicked = true;
ImgClicked=true
});
/*_img1.addEventListener("click", function(){
ImgClicked1 = true;
});
_img2.addEventListener("click", function(){
ImgClicked2 = true;
}); */
_picker.addEventListener("click", function(){
isDatePicked = true;
});
_btn.addEventListener("click", function(){
if(!isImgClicked || !isDatePicked)
{
alert("select the Year and Click the car image");
}
else
{
if((isImgClicked == "_img") && (isDatePicked == "DatePicked"))
{
window.location.replace("sample1.html");
}
else if((isImgClicked == "_img") && (isDatePicked == "DatePicked1"))
{
window.location.replace("sample2.html");
}
else
{
if((isImgClicked == "_img1") && (isDatePicked == "DatePicked"))
{
window.location.replace("sample3.html");
}
else if((isImgClicked == "_img1") && (isDatePicked == "DatePicked1"))
{
window.location.replace("sample4.html");
}
else
{
alert("!!!!");
}
}
}
});
</script>
Here you are assigning isImgClicked = true and ImgClicked = true
img.addEventListener("click", function(){
isImgClicked = true;
ImgClicked=true
});
But you are comparing this boolean with strings. Why?
if((isImgClicked == "_img1") && (isDatePicked == "DatePicked1"))
Fix it.
This is your function re-written in early-return style:
function() {
if(!isImgClicked || !isDatePicked) {
alert("select the Year and Click the car image");
return
}
if((isImgClicked == "_img") && (isDatePicked == "DatePicked")) {
window.location.replace("sample1.html");
return
}
if((isImgClicked == "_img") && (isDatePicked == "DatePicked1")) {
window.location.replace("sample2.html");
return
}
if((isImgClicked == "_img1") && (isDatePicked == "DatePicked")) {
window.location.replace("sample3.html");
return
}
if((isImgClicked == "_img1") && (isDatePicked == "DatePicked1")) {
window.location.replace("sample4.html");
return
}
alert("!!!!");
}
Which if statement are you having a problem with?
I am a very new programmer, and im not used to things more complex than a few if else statements or some light DOM traversing.
With the help of stackoverflow I've created a test for an RPG website im building.
14 questions test the users "concerns" as a player in a dungeons and dragons like setting, and assign points to 1 of 8 personality types.
Each of the 8 types, are the properties of two objects. PrimaryResults and secondaryResults. Each of the 8 properties have the same name.
Defender (def) , Berserker(ber), Monk(mnk) etc (you'll see it in the code)
The point is to be able to get results like Def/Def or Ber/Def or Mnk/Def
there are 8x8 combinations or 64 results.
then one div with the a class of results appends the actual HTML results to the screen for the user based on the final scores of the test.
My Problem:
I need a line of Code that goes through each property of BOTH objects and finds the highest value, I'm trying to put that in an IF statement that results in appending the correct results to the user.
Updated Attempt on 6/5 ---
USing Azamantes' code suggestion, I find that I still get the results of DEF/ DEF no matter what the actual values of each variable are.
I've included a screen shot of what the console.log is telling me about the values vs what the display is bringing up.
For some reason when the code cycles over
If ph =def and sh = def its coming back as true.
In the image I circled a possible issue, I dont know im not an expert.
could it having anything to do with how it says 0 for Ber on the top and has the score for ber when clicked on ? (see picture)
or could it have anything to do with the values of the objects itself? Are the values getting lost in translation somewhere?
$(window).load(function() {
$(".intro").appendTo('#display_box');
var question = $(".question");
var questionPosition = -1;
var results =$(".results");
var secondaryResults = {
def:0,
ber:0,
mnk:0,
rng:0,
cle:0,
thf:0,
mge:0,
dru:0,
};
var primaryResults = {
def:0,
ber:0,
mnk:0,
rng:0,
cle:0,
thf:0,
mge:0,
dru:0,
};
let pH = 'def', sH = 'def';
Object.keys(primaryResults).map(key => {
if(primaryResults[key] > primaryResults[pH]) {
pH = key;
}
if(secondaryResults[key] > secondaryResults[pH]) {
sH = key;
}
});
const highestPrimary = primaryResults[pH];
const highestSecondary = secondaryResults[sH];
$("#submit").on('click', function(){
console.log(primaryResults);
console.log(secondaryResults);
if (pH == 'def' && sH == 'def') {
clearBox();
results.eq(0).fadeIn(500).appendTo('#display_box');
};
if (pH == 'def' && sH == 'ber') {
clearBox();
results.eq(1).fadeIn(500).appendTo('#display_box');
};
if (pH == 'def' && sH == 'mnk') {
clearBox();
results.eq(2).fadeIn(500).appendTo('#display_box');
};
if (pH == 'def' && sH == 'rng') {
clearBox();
results.eq(3).fadeIn(500).appendTo('#display_box');
};
if (pH == 'def' && sH == 'thf') {
clearBox();
results.eq(4).fadeIn(500).appendTo('#display_box');
};
if (pH == 'def' && sH == 'cle') {
clearBox();
results.eq(5).fadeIn(500).appendTo('#display_box');
};
if (pH == 'def' && sH == 'dru') {
clearBox();
results.eq(6).fadeIn(500).appendTo('#display_box');
};
if (pH == 'def' && sH == 'mge') {
clearBox();
results.eq(7).fadeIn(500).appendTo('#display_box');
};
})
function clearBox(){
$("#display_box").children().fadeOut(500).appendTo('#question_holding');
};
function cycle(){
question.eq(questionPosition).fadeIn(500).appendTo("#display_box");
$("#display_box").animate({scrollTop:0}, 500);
}
$('#leftarrow').on('click', function(){
questionPosition--;
if (questionPosition <= -1) {questionPosition = 13};
clearBox();
cycle();
});
$('#rightarrow').on('click', function(){
questionPosition++;
if (questionPosition > 13) { questionPosition = 0};
clearBox();
cycle();
if($('input[name^="answer"]:checked').length > 13 ) {
$("#submit").css('display', 'block');
}
});
$('#submit').on('click', function() {
$('input[name^= "answer"]:checked').each(function(){
if ($(this).val() == "monkL"){
secondaryResults.mnk += 1.02;
}
if ($(this).val() == "berserkerL"){
secondaryResults.ber += .99;
}
if ($(this).val() == "defenderL"){
secondaryResults.def += 1.01;
}
if ($(this).val() == "thiefL"){
secondaryResults.thf += 1;
}
if ($(this).val() == "mageL"){
secondaryResults.mge += .98;
}
if ($(this).val() == "clericL"){
secondaryResults.cle += 1.03;
}
if ($(this).val() == "rangeL"){
secondaryResults.rng += .97;
}
if ($(this).val() == "druidL"){
secondaryResults.dru += 1.05;
}
})
});
$('#submit').on('click', function() {
$('input[name^= "answer"]:checked').each(function(){
if ($(this).val() == "monkM"){
secondaryResults.mnk += 1.31;
}
if ($(this).val() == "berserkerM"){
secondaryResults.ber += 1.29;
}
if ($(this).val() == "defenderM"){
secondaryResults.def += 1.3;
}
if ($(this).val() == "thiefM"){
secondaryResults.thf += 1.28;
}
if ($(this).val() == "mageM"){
secondaryResults.mge += 1.27;
}
if ($(this).val() == "cleric"){
secondaryResults.cle += 1.32;
}
if ($(this).val() == "rangeM"){
secondaryResults.rng += 1.33;
}
if ($(this).val() == "druidM"){
secondaryResults.dru += 1.26;
}
})
});
$('#submit').on('click', function() {
$('input[name^= "answer"]:checked').each(function(){
if ($(this).val() == "monkH"){
secondaryResults.mnk += 1.5;
}
if ($(this).val() == "berserkerH"){
secondaryResults.ber += 1.51;
}
if ($(this).val() == "defenderH"){
secondaryResults.def += 1.52 ;
}
if ($(this).val() == "thiefH"){
secondaryResults.thf += 1.49;
}
if ($(this).val() == "mageH"){
secondaryResults.mge += 1.48;
}
if ($(this).val() == "clericH"){
secondaryResults.cle += 1.47;
}
if ($(this).val() == "rangeH"){
secondaryResults.rng += 1.53;
}
if ($(this).val() == "druidH"){
secondaryResults.dru += 1.51;
}
})
});
$('#submit').on('click', function() {
$('input[name^= "answer"]:checked').each(function(){
if ($(this).val() == "monkPL"){
primaryResults.mnk += .96;
}
if ($(this).val() == "berserkerPL"){
primaryResults.ber += .97;
}
if ($(this).val() == "defenderPL"){
primaryResults.def += .98;
}
if ($(this).val() == "thiefPL"){
primaryResults.thf += .99;
}
if ($(this).val() == "magePL"){
primaryResults.mge += 1;
}
if ($(this).val() == "clericPL"){
primaryResults.cle += 1.01;
}
if ($(this).val() == "rangePL"){
primaryResults.rng += 1.02;
}
if ($(this).val() == "druidPL"){
primaryResults.dru += 1.03;
}
})
});
$('#submit').on('click', function() {
$('input[name^= "answer"]:checked').each(function(){
if ($(this).val() == "monkP"){
primaryResults.mnk += 1.3;
}
if ($(this).val() == "berserkerPM"){
primaryResults.ber += 1.26;
}
if ($(this).val() == "defenderPM"){
primaryResults.def += 1.27;
}
if ($(this).val() == "thiefPM"){
primaryResults.thf += 1.28;
}
if ($(this).val() == "magePM"){
primaryResults.mge += 1.29;
}
if ($(this).val() == "clericPM"){
primaryResults.cle += 1.31;
}
if ($(this).val() == "rangePM"){
primaryResults.rng += 1.32;
}
if ($(this).val() == "druidPM"){
primaryResults.dru += 1.33;
}
})
});
$('#submit').on('click', function() {
$('input[name^= "answer"]:checked').each(function(){
if ($(this).val() == "monkPH"){
primaryResults.mnk += 1.46;
}
if ($(this).val() == "berserkerPH"){
primaryResults.ber += 1.47;
}
if ($(this).val() == "defenderPH"){
primaryResults.def += 1.48 ;
}
if ($(this).val() == "thiefPH"){
secondaryResults.thf += 1.49;
}
if ($(this).val() == "magePH"){
primaryResults.mge += 1.5;
}
if ($(this).val() == "clericPH"){
primaryResults.cle += 1.51;
}
if ($(this).val() == "rangePH"){
primaryResults.rng += 1.52;
}
if ($(this).val() == "druidPH"){
primaryResults.dru += 1.536172;
}
$("#submit").css('display','none');
})
});
});
Screen cap of results
If I understood you, this is what you need:
let primaryResults = {
def: 0, ber: 5, mnk: 99999,
rng: 0, cle: 1, thf: 1,
mge: 0, dru: 1,
};
let secondaryResults = {
def: 1, ber: 0, mnk: 0,
rng: 1, cle: 33333333, thf: 0,
mge: 1, dru: 0,
};
let pH = 'def', sH = 'def';
let highestPrimary, highestSecondary;
Object.keys(primaryResults).map(key => {
if(primaryResults[key] > primaryResults[pH]) {
pH = key;
}
if(secondaryResults[key] > secondaryResults[sH]) {
sH = key;
}
});
highestPrimary = primaryResults[pH];
highestSecondary = secondaryResults[sH];
pH - key in primaryResults with the highest value
sH - key in resultsResults with the highest value
highestPrimary - the highest value in primaryResults
highestSecondary - the highest value in secondaryResults
I am making a javascript code that has a button and when I click on it, it displays one of 5 symbols but when I click the button, it shows the random symbol but the button disapears. I'm new to javascript so can I please get some help?
<script>
function slots()
{
var slot1 = Math.floor(Math.random()*5);
if (slot1 == 0) {
document.write("\u2663");
}
if (slot1 == 1) {
document.write("\u2665");
}
if (slot1 == 2) {
document.write("\u2666");
}
if (slot1 == 3) {
document.write("\u2660");
}
if (slot1 == 4) {
document.write("7");
}
}
</script>
<button type="button" value="Spin" name="SPIN"onClick="slots(); return false;"></button>
When you write document.write() the screen refreshes, so I guess you could do something like this:
<script>
function slots()
{
var slot1 = Math.floor(Math.random()*5);
if (slot1 == 0) {
document.getElementById('value').innerHTML = "\u2663";
}
if (slot1 == 1) {
document.getElementById('value').innerHTML = "\u2665";
}
if (slot1 == 2) {
document.getElementById('value').innerHTML = "\u2666";
}
if (slot1 == 3) {
document.getElementById('value').innerHTML = "\u2660";
}
if (slot1 == 4) {
document.getElementById('value').innerHTML = "7";
}
}
</script>
<button type="button" value="Spin" name="SPIN" onClick="slots();">Click</button>
<span id="value"></span>
Slightly optimized version of otrebla's code, see it in action:
function slots() {
var slot1 = Math.floor(Math.random() * 5);
var value = document.getElementById('value');
switch (slot1) {
case 0:
value.innerHTML = "\u2663";
break;
case 1:
value.innerHTML = "\u2665";
break;
case 2:
value.innerHTML = "\u2666";
break;
case 3:
value.innerHTML = "\u2660";
break;
case 4:
value.innerHTML = "7";
break;
}
}
<button type="button" value="Spin" name="SPIN" onClick="slots();">Click</button>
<span id="value"></span>
I am making a Snake game so I'm trying to move my snake. It is moving with keys but it should move automatically on the screen. I tried doing that with while loops like in the code below but because of break; I have to press a key every time I want it to move. How can I make it move automatically? I tried removing break; an using an if statement but I didn't succeed.
Any other solutions or something else?
I'm new to programming so any advices would be helpful.
var main = function() {
var i = 0;
var j = 0;
$(document).keyup(function(event) {
var e = event.which;
while(i == 1) {
$('.snake').animate({left: '+=10px'}, 10);
break;
}
while(i == 2) {
$('.snake').animate({left: '-=10px'}, 10);
break;
}
while(i == 3) {
$('.snake').animate({top: '-=10px'}, 10);
break;
}
while(i == 4) {
$('.snake').animate({top: '+=10px'}, 10);
break;
}
//Which key is preesed
//D
if(e == 68) {
i = 1;
}
//A
else if(e == 65) {
i = 2;
}
//W
else if(e == 87) {
i = 3;
}
//S
else if(e == 83) {
i = 4;
}
//Any other key
else {
i = 0;
}
});
};
$(document).ready(main);
I think you just have to organize a little bit your code.
First. You must put your code inside a function. You really don't need a while. You can use a simple if.
function move(i) {
if(i == 1) {
$('.snake').animate({left: '+=10px'}, 10);
break;
}
if(i == 2) {
$('.snake').animate({left: '-=10px'}, 10);
break;
}
if(i == 3) {
$('.snake').animate({top: '-=10px'}, 10);
break;
}
if(i == 4) {
$('.snake').animate({top: '+=10px'}, 10);
break;
}
}
Now you have to change the event, using keydown instead of keyup
function main() {
var interval;
$(document).keydown(function(event) {
if(interval) clearInterval(interval); // Clear the previous interval
var e = event.which;
var i;
//Which key is pressed
//D
if(e == 68) {
i = 1;
}
//A
else if(e == 65) {
i = 2;
}
//W
else if(e == 87) {
i = 3;
}
//S
else if(e == 83) {
i = 4;
}
//Any other key
else {
i = 0;
}
interval = setInterval(function() {
move(i)
},1000); // repeat every 1 second
});
}
$(document).ready(main);