I'm making a simple game in HTML/Javascript where everytime a button or hyperlink gets pressed it adds 1 to a counter
<script type="text/javascript">
var count = 0;
function countClicks() {
count = count + 1;
document.getElementById("p2").innerHTML = count;
}
</script>
My question is is there a way to also add a tick (Ascii #10004) equal to the number in the counter. I'm sure this is an easy solve but I've never really used Javascript and this seems the easiest language to do this all in. I appreciate any help given
You can use the HTML decimal: ☑
Just replace the code:
document.getElementById("p2").innerHTML = count;
with the following code:
document.getElementById("p2").innerHTML = "☑ "+count;
Or you can use:
document.getElementById("p2").innerHTML = "✔ "+count;
The result will be like this:
✔ 5
here 5 is your count.
Yes you can. You even don't need a loop to concatenate ticks.
see jsfiddle demo
var count = 5; // count is already 5 for demo purpose
function countClicks() {
count = count + 1;
var ticks = Array(count+1).join("✔");
document.getElementById("p2").innerHTML = count+' '+ticks;
}
countClicks(); # 6 ✔✔✔✔✔✔
Yes, you can use the String.fromCharCode to convert ascii code to character.
Example to display continuos ticks equal to number of count:
<script type="text/javascript">
var count = 0;
function countClicks() {
count = count + 1;
var res = String.fromCharCode(10004);
var output = "";
for (var i = 0; i < count; i++) {
output += res+" ";
}
document.getElementById("p2").innerHTML = output;
}
</script>
This will do :
http://jsfiddle.net/oL83m567/1/
var count = 0;
function countClicks() {
count = count + 1;
var tick='';
for(var i=0;i<count;i++)
tick+= '✔';
document.getElementById("p2").innerHTML = count + tick;
}
It sounds like you want to ADD another tick every time the thing is pressed? I would do it like this:
var count = 0;
function countClicks() {
count = count + 1;
document.getElementById("p2").innerHTML = document.getElementById("p2").innerHTML + '✔';
}
Or, slightly more efficiently:
var p2, count = 0;
function countClicks() {
count = count + 1;
p2 = document.getElementById("p2");
p2.innerHTML = p2.innerHTML + '✔';
}
In that case, count becomes unnecessary, unless you need it for something else.
I'd go for doing it with an array. Advantage of this is that you have the ticks stored as elements in the array and can manipulate them later e.g. change a chosen tick to a cross or have a button which removes a tick. Something like:
<script type="text/javascript">
var ticks=new Array();
function countClicks() {
ticks[ticks.length]="✔";
document.getElementById("p2").innerHTML = ticks.join("");
}
</script>
Related
I am supposed to create a triangle of Xs as depicted in the link by using padString image of 20 lines of Xs starting with one X and incrementing by one X for each additional line
The hint they gave was that I am supposed to use something like...
let str = "";
str = str.padStart(i,”x”); // i is the loop counter
What I have so far is this...
let xShape = "x";
for (let counter = 0; counter <= 20; counter = counter + 1) {
xShape = xShape + "x"
}
document.getElementById("demo").innerHTML =
xShape.padStart(xShape, "x");
<p id="demo"></p>
But that doesn't write out 20 lines of Xs starting with the first line having only one X with each new line having an additional X. It only writes the last line of 20 Xs. How do I get it to write all 20 lines? I am a beginner, and am doing this to learn. Thank you so much for your help.
padStart takes the string passed to it, and pads the beginning with the first argument as many times as the second argument.
So you can add it to a loop and just pass it an empty string so it will always have an empty starting point.
let xShape = "";
for (let counter = 0; counter <= 20; counter++) {
xShape += "".padStart(counter, "x") + "<br>";
}
document.getElementById("demo").innerHTML = xShape;
<div id="demo"></div>
You'll have to collect output lines in the loop somehow. But your use of padStart is also wrong: the first argument should not be a string, but a number. It should actually be your loop counter.
let lines = [];
for (let counter = 1; counter <= 20; counter = counter + 1) {
lines.push("".padStart(counter, "x"));
}
document.getElementById("demo").innerHTML = lines.join("<br>");
<p id="demo"></p>
Note that the method repeat is more natural here:
let lines = [];
for (let counter = 1; counter <= 20; counter = counter + 1) {
lines.push("x".repeat(counter));
}
document.getElementById("demo").innerHTML = lines.join("<br>");
<p id="demo"></p>
In a more functional approach:
document.getElementById("demo").innerHTML =
Array.from({length:20}, (_, counter) => "x".repeat(counter+1))
.join("<br>");
<p id="demo"></p>
I am trying to use a for loop for 10 questions with an if condition. The continue is used to pass the one which is not match with condition.
My purpose is to randomly come up 10 question equations which results should be integers, but my code gives me only correct condition with a variable number of questions.
When the condition is not met, it will pass current equation, therefore sometimes I have end up with only 5 or 7 questions because the other 5 or 3 did not pass the condition.
How can I make sure that number of random equation generate is always the same, so that if a the condition is not met, the function will redo random amount of actions to end up with 10 questions?
my code is :
<body>
<p>this is testing for random number meet creteria</p>
<button class = "button" onclick = "myFunction()">try me</button>
<p id = "demo">Thisis where to display question</p>
<script>
function myFunction() {
var quiz = "";
var xNumber;
var yNumber;
var sign = ["+", "-", "*", "/"];
for (var i=0; i<10; i++) {
var xNumber = Math.floor(Math.random()*10);
var yNumber = Math.floor(Math.random()*10);
var randomSign = sign[Math.floor(Math.random()*sign.length)];
var result = eval(xNumber + randomSign + yNumber);
if (Number.isInteger(result)) {
quiz += xNumber + randomSign + yNumber + "<br>";
} else {
continue;
}
}
document.getElementById("demo").innerHTML = quiz;
}
</script>
Change your loop to be conditional on getting the number of items you want.
var numQuestions = 10, counter = 0
while (counter < numQuestions) {
var xNumber = Math.floor(Math.random()*10);
var yNumber = Math.floor(Math.random()*10);
var randomSign = sign[Math.floor(Math.random()*sign.length)];
var result = eval(xNumber + randomSign + yNumber);
if (Number.isInteger(result)) {
quiz += xNumber + randomSign + yNumber + "<br>";
// increment your counter here since you've added another question
counter ++;
}
}
Hello im new to javascript. My function is suppose to increase my count by 1 every-time i call it but when i run it in console it just repeats 1. Any suggestions?
var output = [];
var count = 1;
function bizzBuzz(){
output.push(count);
count++;
console.log(output);
}
bizzBuzz();
var count = 0;
var output = [];
function bizzBuzz() {
output.push(count += 1);
console.log(output);
}
bizzBuzz();
bizzBuzz();
This is my code. I know that it is wrong but I need some help to start a prompt list. My goal is to get 4 marks with a button then you input and have it in an array. It then gets averaged and that gets shown with an alert.
<html>
<head>
<title>Quiz</title>
</head>
<body>
Average your marks
<button onclick="myFunction()">Start</button>
<script type="text/javascrypt">
var student = []
var student[0] = prompt("Name:");
var student[1] = prompt("mark=");
var student[2] = prompt("mark=");
var student[3] = prompt("mark=");
var student[4] = prompt("mark=");
var student[5] = student[1] + student[2] + student[3] + student[4] / 4;
function myFunction() {
if (confirm(student) == true)
}
</script>
</body>
</html>
i actually think you are almost there:
change every avArray to student. and the first time to var student = []
edit:
also write function instead of fuction
edit 2
finally: because you use var you define a variable. so only use var with var student = []
var student[0] is wrong because student is already defined. so use student[0] =
Because prompt always returns a string you want to use Number to make it a number that you can calculate with.
So your final code would look something like this:
var name = prompt("Name:");
var grades = [];
grades[0] = Number(prompt("mark="));
grades[1] = Number(prompt("mark="));
grades[2] = Number(prompt("mark="));
grades[3] = Number(prompt("mark="));
var average = (grades[0] + grades[1] + grades[2] + grades[3]) / 4;
function myFunction() {
confirm(name + ": " + average)
}
Average your marks:
<button onclick="myFunction()">Start</button>
You want to make sure that you are adding int values, not String values - which are the return result of prompt.
Try this:
// Forces the user to input an int by retrying until an int is input
function intPrompt(msg) {
while (true) {
var num = parseInt(prompt(msg));
if (!isNaN(num)) return num;
}
}
Now here's the code that will read 4 marks from the user and average them:
alert((intPrompt('mark 1') + intPrompt('mark 2') + intPrompt('mark 3') + intPrompt('mark 4')) / 4);
Quite a few errors, here are some I've spotted so far:
<script type="text/javascrypt">
Spell javascript correctly
var student[0] = prompt("Name:");
You use var only when defining the student the first time, remove it from the next appearances of student.
if (confirm(student) == true)
Student is an array, not a string. You will need to convert it to a string in some way to use it for confirm AFAIK.
var student[5] = student[1] + student[2] + student[3] + student[4] / 4;
I just tested this line out, and averaging doesn't work correctly, you need to prevent concatenation, maybe proper brackets.
Calculation of average is not the perfect one and you try to put everything into array, even if it does not belong there.
Check the example: http://codepen.io/anon/pen/rWxMEP
<html>
<head>
<title>Quiz</title>
<body>
Average your marks<button onclick=myFunction()>Start</button>
<script type="text/javascrypt">
let name;
let studentMarks = [];
const numOfMarks = 4;
let sumMark = 0;
let msg;
let myFunction = function() {
name = prompt("Name");
if (name.length !== 0){
for(i = 0; i < numOfMarks; i++){
msg = "Enter mark (" + parseInt(parseInt(numOfMarks)-parseInt(i) )+" left)";
studentMarks[i] = prompt(msg);
sumMark += parseFloat(studentMarks[i]);
}
alert(name + "'s average mark is "+ sumMark/numOfMarks);
}
}
</script>
</body>
</html>
I am supposed to write a function which can count the words in the text area but my code count only the first word, you can see the code here:
link to my code
var myTextareaElement = document.getElementById("myWordsToCount");
myTextareaElement.onkeyup = function wordcount(wor){
var myTextareaElement =document.getElementById("myWordsToCount").value;
var haveByNow = 0;
for (var i = 0; i < wordcount.length; i++)
if (wor[i] === " ") {
haveByNow = +1;
}
haveByNow += 1;
document.getElementById("wordcount").innerHTML = haveByNow;
}
Why not splitting on empty character that textarea value and get arraylength: Check the snippet below
var myTextareaElement = document.getElementById("myWordsToCount");
myTextareaElement.onkeyup = function wordcount(wor) {
var myText = this.value.trim();
var wordsArray = myText.split(/\s+/g);
var words = wordsArray.length;
document.getElementById("wordcount").innerHTML = words;
};
<textarea id="myWordsToCount"></textarea>
<span id="wordcount"></span>
You have some typos and errors, see working code:
var myTextareaElement = document.getElementById("myWordsToCount");
myTextareaElement.onkeyup = function wordcount(wor){
var words = myTextareaElement.value;
var haveByNow = 1;
for (var i = 0; i < words.length; i++) {
if (words[i] == " ") {
haveByNow += 1;
}
}
document.getElementById("wordcount").innerHTML = haveByNow;
}
<textarea id="myWordsToCount" rows="5" cols="60"></textarea><br>
The wordcount is: <span id="wordcount"></span><br>
This line:
haveByNow = +1;
...is not the same as:
haveByNow += 1;
The former sets haveByNow to 1, the other increments. This is why you'd be seeing a result of 1 every time.
Another problem is this expression in your for loop:
wordcount.length
wordcount is the name of your function, and wordcount.length is the number of parameters of that function, which is not going to be what you want. myTextareaElement, which is the value of the input is what you want to get the length of:
for (var i = 0; i < myTextareaElement.length; i++) ...
Though as #itsgoingdown points out, there are better ways to get a word count.