JavaScript - If statement with text doesn't work properly - javascript

I am trying to make an if statement based off of user input. I can't seem to get this code to work. It continues to say no, even when I enter 'one', which is supposed to do something different, as you can see in the code snippet. I am running the code in the latest version of Chrome.
var ques = document.getElementById("question");
var ansBox = document.getElementById("ansBox").value;
var submitBtn = document.getElementById("submitBtn");
var isCorrect = document.getElementById("isCorrect");
var num1 = Math.floor((Math.random() * 100) + 1);
var num2 = Math.floor((Math.random() * 100) + 1);
var ans = num1 + num2;
function question() {
ques.innerHTML = num1 + " + " + num2;
}
function checkAns() {
if(ansBox.value == "one") {
isCorrect.innerHTML = "Yes";
} else {
isCorrect.innerHTML = "No";
}
}
question();
body {
font-family: Arial;
}
div {
padding-top: 50px;
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div>
<h1>Edu Game One</h1>
<h3 id="question"></h3>
<input type="text" id="ansBox" />
<button id="submitBtn" onclick="checkAns()">Submit</button>
<p id="isCorrect"></p>
</div>
<script src="scripts.js"></script>
</body>
</html>

You had an extra .value at the end of your definition of ansBox. Removing that makes it work:
var ques = document.getElementById("question");
var ansBox = document.getElementById("ansBox");
var submitBtn = document.getElementById("submitBtn");
var isCorrect = document.getElementById("isCorrect");
var num1 = Math.floor((Math.random() * 100) + 1);
var num2 = Math.floor((Math.random() * 100) + 1);
var ans = num1 + num2;
function question() {
ques.innerHTML = num1 + " + " + num2;
}
function checkAns() {
if(ansBox.value == "one") {
isCorrect.innerHTML = "Yes";
} else {
isCorrect.innerHTML = "No";
}
}
question();
body {
font-family: Arial;
}
div {
padding-top: 50px;
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div>
<h1>Edu Game One</h1>
<h3 id="question"></h3>
<input type="text" id="ansBox" />
<button id="submitBtn" onclick="checkAns()">Submit</button>
<p id="isCorrect"></p>
</div>
<script src="scripts.js"></script>
</body>
</html>

Related

Selectable() Jquery mobile alternative

I was looking for the solution for my API but I couldn't find.. All examples or advices didn't work. Could somebody help me out? Or give me any suggestion? I'm still studying JQuery, so any help would be more than welcome..
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>New api</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<main>
<section>
<div id="alert"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<ul id="wordblock">
</ul>
<div id="result">Result</div>
</section>
<script src="./api.js"></script>
</main>
</body>
</html>
JQuery code:
function screenResolutionAlert(x) {
if (x.matches) {
$("#alert").html("This API doesn't work with touchpads <br> (mobiles, tablets etc) <br> please use computer or laptop with a mouse").show();
} else {
$("#alert").hide();
}
}
var x = window.matchMedia("(max-width: 1200px)")
screenResolutionAlert(x)
x.addListener(screenResolutionAlert)
//API swap words code
$(function () {
$("#wordblock").sortable();
$("#wordblock").disableSelection();
const array = ["pierogi", "gołąbki", "pies", "sześcian"];
const word = array[Math.floor(Math.random() * array.length)];
let d_word = word.split('');
shuffle(d_word);
const lis = [];
for (let i = 0; i < d_word.length; i++) {
lis.push('<li class="ui-state-default">' + d_word[i] + '</li>')
}
$('#wordblock').html(lis.join(''));
$('#wordblock').mouseup(function () {
setTimeout(() => {
let r_word = '';
$('#wordblock>li').each(function (e) {
r_word += $(this).text();
});
if (r_word == word) {
$("#result").html(`Correct! It was exactly "${r_word}"`);
} else {
$("#result").html(`Wrong! keep trying.. <br> it's not "${r_word}"`);
}
}, 0);
});
});
function shuffle(a, b, c, d) {
c = a.length;
while (c) b = Math.random() * (--c + 1) | 0, d = a[c], a[c] = a[b], a[b] = d
}
Yes I was using mobile Jquery links, didn't work... And any versions of.. I tried everything what was written in the internet ;(
I tried your code and ...it seems to work! Snippet is here below, just press Run code snippet, and order letters to "PIES".
I suggest you to read about APIs, because at the moment you're not using any API at all! 😁
function screenResolutionAlert(x) {
if (x.matches) {
$("#alert")
.html(
"This API doesn't work with touchpads <br> (mobiles, tablets etc) <br> please use computer or laptop with a mouse"
)
.show();
} else {
$("#alert").hide();
}
}
var x = window.matchMedia("(max-width: 1200px)");
screenResolutionAlert(x);
x.addListener(screenResolutionAlert);
//API swap words code
$(function () {
$("#wordblock").sortable();
$("#wordblock").disableSelection();
const array = ["pies"];
const word = array[Math.floor(Math.random() * array.length)];
let d_word = word.split("");
shuffle(d_word);
const lis = [];
for (let i = 0; i < d_word.length; i++) {
lis.push('<li class="ui-state-default">' + d_word[i] + "</li>");
}
$("#wordblock").html(lis.join(""));
$("#wordblock").mouseup(function () {
setTimeout(() => {
let r_word = "";
$("#wordblock>li").each(function (e) {
r_word += $(this).text();
});
if (r_word == word) {
$("#result").html(`Correct! It was exactly "${r_word}"`);
} else {
$("#result").html(`Wrong! keep trying.. <br> it's not "${r_word}"`);
}
}, 0);
});
});
function shuffle(a, b, c, d) {
c = a.length;
while (c)
(b = (Math.random() * (--c + 1)) | 0),
(d = a[c]),
(a[c] = a[b]),
(a[b] = d);
}
ul#wordblock {
padding-left: 0;
}
ul#wordblock li {
display: inline-block;
font-size: 2em;
padding: 0.2em 0.2em;
cursor: pointer;
background-color: aliceblue;
border-radius: 50%;
margin: 0.5em;
width: 1em;
height: 1em;
text-align: center;
line-height: 0.9em;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>New api</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<main>
<section>
<div id="alert"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<ul id="wordblock">
</ul>
<div id="result">Result</div>
</section>
<script src="./api.js"></script>
</main>
</body>
</html>

javascript hide test/pictures

I use this to hide my answers from the flashcards. However, when I start up the webpage all the answers are showing and I have to manually hide them. HOw do I get everything hidden when I startup or open up the webpage.
I need the answers hidden
function myShowText(id) {
document.querySelector('#' + id + ' .answer').style.color = 'black';
}
function myHideText(id) {
document.querySelector('#' + id + ' .answer').style.color = 'white';
}
.answer {
border-style: solid;
border-color: #287EC7;
color: white;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> Flashcards VBA </title>
<rel="stylesheet" href="css/styles.css">
</head>
<body>
<script src="js/scripts.js"></script>
<h3> Flashcards </h3>
<p class="question">
The first question
</p>
<div id="bash_start">
<p class="answer">
<img src="image.jpg">
</p>
</div>
</body>
</html>
Just add display: none in the css.
.answer {
border-style: solid;
border-color: #287EC7;
color: white;
display: none;
}
Hide the answer on window.onload
window.onload=function(){
document.querySelector('.answer').style.visibility = "hidden";
}
window.onload=function(){
document.querySelector('.answer').style.visibility = "hidden";
}
function myShowText(id) {
document.querySelector('#' + id + ' .answer').style.color = 'black';
}
function myHideText(id) {
document.querySelector('#' + id + ' .answer').style.color = 'white';
}
.answer {
border-style: solid;
border-color: #287EC7;
color: white;
}
<html lang="en">
<body>
<script src="js/scripts.js"></script>
<h3> Flashcards </h3>
<p class="question">
The first question
</p>
<div id="bash_start">
<p class="answer">
<img src="image.jpg">
</p>
</div>
</body>
</html>
You can try the below code. hideAnswers() should be called on page start script. Then you can display answers using showAnswers()
function hideAnswers(){
var answers = document.getElementsByClassName("answer");
var answer;
for(var i = 0; i <= answers.length-1; i++){
answer = answers[i];
answer.style.visibility = "hidden";
}
}
function showAnswers(){
var answers = document.getElementsByClassName("answer");
var answer;
for(var i = 0; i <= answers.length-1; i++){
answer = answers[i];
answer.style.visibility = "visible";
}
}

Check if the last characters in a string or inputs are similar to each other in javascript [duplicate]

This question already has answers here:
Compare two last character in a string
(2 answers)
Closed 4 years ago.
I'm trying to create a simple add calculator. As of now I am successful on displaying the numbers and concatenating them. But I what I don't want is when I clicked the plus(add) button two or more times, it will also concatenate with another plus symbol. Is there a way for me that if ever I clicked the plus button twice. the second symbol will no longer display. Like if it detects that the previous input is a plus symbol. it will never concatenate with each other. Sorry if my English is not clear.
Sample Error when i clicked the add button multiple times: ( 111++++222 ) instead of just 111+222
Here's my code guys:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
body {
margin: 0px auto;
width: 600px;
}
p {
font-size: 23px;
float: left;
padding: 30px;
border: solid #336336 2px;
margin: 20px;
}
</style>
</head>
<body>
<h1 id="result">aaww </h1>
<p id="1" class="one">1</p>
<p id="2" class="two">2</p>
</br></br>
<p id="add">+</p>
</br></br>
<p id="equals">=</p>
<!-- <p class="cancel">cancel</p> <p class="cancel">cancel</p> -->
<p class="clear-tasks"> CLEAR</p>
<script>
//PLACE HOLDER FOR THE RESULT
let Result = document.getElementById("result");
Result.innerText = "RESULT HERE";
// CLEAR BUTTON
let clear = document.querySelector('.clear-tasks');
// EVENT LISTENER TO CLEAR THE BUTTON
clear.addEventListener('click', function(){
Result.textContent = '';
});
let addition = document.querySelector("#add");
addition.addEventListener('click',runEventAdd);
function runEventAdd(e){
Result.textContent += ' + ';
}
//ONE BUTTON
const numberOne = document.querySelector('.one');
// EVENT LISTENER TO CONCATINATE 1
numberOne.addEventListener('click', runEvent);
function runEvent(e) {
if (Result.textContent === 'RESULT HERE') {
Result.textContent = 1;
} else {Result.textContent += 1;
}
}
//TWO BUTTON
const numberTwo = document.querySelector('.two');
// EVENT LISTENER TO CONCATINATE 2
numberTwo.addEventListener('click', runEvent2);
function runEvent2(e) {
if (Result.textContent === 'RESULT HERE') {
Result.textContent = 2;
} else {Result.textContent += 2;
}
}
</script>
</body>
</html>
Just use endsWith to check if the current string ends with a +:
addition.addEventListener('click',runEventAdd);
function runEventAdd(e){
if (!Result.textContent.endsWith(' + '))
Result.textContent += ' + ';
}
Use an if statement to check if there is already an operator. I made something similar in Java with GUI instead of JS but thats what I did and it worked fine. If you do the if statement you could use if(str.indexOf(operator) == -1) {
do the concatenation.
Check the last value of your result. If it is a '+', don't add another '+'
//PLACE HOLDER FOR THE RESULT
let Result = document.getElementById("result");
Result.innerText = "RESULT HERE";
// CLEAR BUTTON
let clear = document.querySelector('.clear-tasks');
// EVENT LISTENER TO CLEAR THE BUTTON
clear.addEventListener('click', function(){
Result.textContent = '';
});
let addition = document.querySelector("#add");
addition.addEventListener('click',runEventAdd);
function runEventAdd(e){
if(Result.innerText.slice(-1) != '+')
{
Result.textContent += ' + ';
}
}
//ONE BUTTON
const numberOne = document.querySelector('.one');
// EVENT LISTENER TO CONCATINATE 1
numberOne.addEventListener('click', runEvent);
function runEvent(e) {
if (Result.textContent === 'RESULT HERE') {
Result.textContent = 1;
} else {Result.textContent += 1;
}
}
//TWO BUTTON
const numberTwo = document.querySelector('.two');
// EVENT LISTENER TO CONCATINATE 2
numberTwo.addEventListener('click', runEvent2);
function runEvent2(e) {
if (Result.textContent === 'RESULT HERE') {
Result.textContent = 2;
} else {Result.textContent += 2;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
body {
margin: 0px auto;
width: 600px;
}
p {
font-size: 23px;
float: left;
padding: 30px;
border: solid #336336 2px;
margin: 20px;
}
</style>
</head>
<body>
<h1 id="result">aaww </h1>
<p id="1" class="one">1</p>
<p id="2" class="two">2</p>
</br></br>
<p id="add">+</p>
</br></br>
<p id="equals">=</p>
<!-- <p class="cancel">cancel</p> <p class="cancel">cancel</p> -->
<p class="clear-tasks"> CLEAR</p>
</body>
</html>

JavaScript Craps game using two arrays to generate the "point"

There are no errors on plnkr.co, yet the div button still doesn't work.
1) Am I on the right track for pulling two random numbers from two arrays, adding them and returning the result when the button is clicked.
2) I saw the undefined error when I ran the code on here, but I am not sure what to troubleshoot. The code didn't give any errors on plnkr.co.
//button event will generate 2 random numbers and add them together
var num1 = [1,2,3,4,5,6];
var num2 = [1,2,3,4,5,6];
//var sum1 = [2,3,4,5,6,7,8,9,10,11,12]
//var sum2 = num1 + num2
function rollDice(){
var randomNumber = Math.floor(Math.random()*(num1 + num2));
document.getElementById("roll").innerHTML = randomNumber[rollDice];
}
body {
background-color: darkred;
}
h1 {
color: white;
text-align: center;
}
p {
color: white;
font-family: verdana;
font-size: 20px;
}
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>JavaScript Craps using arrays</title>
<link rel="stylesheet" href="random.css">
<script src="craps.js"></script>
</head>
<body>
<h1> Craps Lounge</h1>
<div id="button">
<button onclick="randomNumber()">Roll the Bones</button>
</div>
<p id="roll"></p>
</body>
</html>
A few issues with your code:
you need to actually call rollDice() function.
you can't find randomNumber like that, you need two random index to select two numbers from the two arrays you have defined. you can use Math.random() for this, like in the code below:
randomNumber[rollDice] is wrong since randomNumber is a number and not an object.
//button event will generate 2 random numbers and add them together
var num1 = [1,2,3,4,5,6];
var num2 = [1,2,3,4,5,6];
//var sum1 = [2,3,4,5,6,7,8,9,10,11,12]
//var sum2 = num1 + num2
function rollDice(){
var randomIndex1 = Math.floor(Math.random()*num1.length);
var randomIndex2 = Math.floor(Math.random()*num2.length);
var randomNumber = num1[randomIndex1] + num2[randomIndex2];
document.getElementById("roll").innerHTML = randomNumber;
}
body {
background-color: darkred;
}
h1 {
color: white;
text-align: center;
}
p {
color: white;
font-family: verdana;
font-size: 20px;
}
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>JavaScript Craps using arrays</title>
<link rel="stylesheet" href="random.css">
<script src="craps.js"></script>
</head>
<body>
<h1> Craps Lounge</h1>
<div id="button">
<button onclick="rollDice()">Roll the Bones</button>
</div>
<p id="roll"></p>
</body>
</html>
I seen a few things. I refactored to what I believe you was trying to achieve.
//button event will generate 2 random numbers and add them together
var num1 = [1, 2, 3, 4, 5, 6];
var num2 = [1, 2, 3, 4, 5, 6];
//var sum1 = [2,3,4,5,6,7,8,9,10,11,12]
//var sum2 = num1 + num2
function rollDice() {
//random # between 1 and 6
var dice1 = Math.floor((Math.random() * num1.length) + 1);
var dice2 = Math.floor((Math.random() * num2.length) + 1);
var randomNumber = dice1 + dice2;
document.getElementById("roll").innerHTML = randomNumber;
}
body {
background-color: darkred;
}
h1 {
color: white;
text-align: center;
}
p {
color: white;
font-family: verdana;
font-size: 20px;
}
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>JavaScript Craps using arrays</title>
</head>
<body>
<h1> Craps Lounge</h1>
<div id="button">
<button onclick="rollDice()">Roll the Bones</button>
</div>
<p id="roll"></p>
</body>
</html>

Creating shapes in an SVG

For my assignment, we create an SVG block and the user would input a number, and we add that number of squares to the svg block in random positions within the svg block. My code isn't working.
Here's my html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<script src="http://cmpt165.csil.sfu.ca/js/jquery-3.1.0.js"></script>
<script src="http://cmpt165.csil.sfu.ca/js/raphael-2.1.4.js"></script>
<script src="logic.js"></script>
<link rel="stylesheet" href="style.css" />
<title>Exercise 10</title>
</head>
<body>
<h1>Exercise 10</h1>
<div id="svg1"></div>
<div class="form">Add how many?
<input type="text" id="howmany" />
<button id="more">Add More</button></div>
<div id="svg2"></div>
<div class="form">
<button id="another">Add Another</button>
</div>
</body>
</html>
Here's my Javascript:
var num_squares, x, y;
num_squares = $('#howmany').val()
add_more = function() {
for (count = 0;count < num_squares;count += 1)
{
x = Math.random() * 180
y = Math.random() * 180
r = paper.rect(x, y, 20, 20)
filled = {
'fill': '#ddf'
}
r.attr(filled)
}
}
setup = function() {
paper = Raphael('svg1', 200, 200)
add_more()
}
jQuery(document).ready(setup)
Here's my CSS:
#svg1 {
border: black;
}
You initialise num_squares outside the function i.e. on document load. This is before anyone's typed in a number so num_squares is always empty and therefore your loop doesn't do anything. You also aren't calling add_more when the button is pressed.
add_more = function() {
var num_squares, x, y;
num_squares = $('#howmany').val();
for (count = 0;count < num_squares;count += 1)
{
x = Math.random() * 180
y = Math.random() * 180
r = paper.rect(x, y, 20, 20)
filled = {
'fill': '#ddf'
}
r.attr(filled)
}
}
setup = function() {
paper = Raphael('svg1', 200, 200)
}
jQuery(document).ready(setup)
#svg1 {
border: black;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<script src="http://cmpt165.csil.sfu.ca/js/jquery-3.1.0.js"></script>
<script src="http://cmpt165.csil.sfu.ca/js/raphael-2.1.4.js"></script>
<script src="logic.js"></script>
<link rel="stylesheet" href="style.css" />
<title>Exercise 10</title>
</head>
<body>
<h1>Exercise 10</h1>
<div id="svg1"></div>
<div class="form">Add how many?
<input type="text" id="howmany">
<button id="more" onclick="add_more()">Add More</button></div>
<div id="svg2"></div>
<div class="form">
<button id="another">Add Another</button>
</div>
</body>
</html>

Categories

Resources