I was working on this code, and I got stuck here as a JS rookie and need help. How would you rewrite this block, using % operator, instead of if statement?
<!DOCTYPE html>
<html>
<head>
<script>
window.onload=function(){
var letters = ["A","B","C"]
var counter = 0;
var timer=setInterval(
function(){
counter= counter+1;
if (counter==letters.length){
counter=0;
}
document.getElementById("demo").value=letters[counter];
},1000)
}
</script>
</head>
<body>
<input type="text" id="demo" value="A">
</body>
</html>
Simple use it after doing your add operation to return the remains after division (or modulus):
const letters = ["A","B","C"]
let counter = 0;
setInterval(function(){
counter = (counter+1) % letters.length;
document.getElementById("demo").value = letters[counter];
}, 1000);
<input type="text" id="demo" value="A" />
Couple of other tips, use const if the values don't change (like your array), and let if it can definitely change. Also, you don't need to store your interval here as you never cancel it, so no need for const timer in that case. Simplifies the code a lot!
Related
DISCLAIMER: i'm legit a newbie
I have a 2nd parameter in the getInput function, I should use it for the 9 zeros that I should input. But I don't know how to loop it to become 9 zeros instead of putting it in a variable.
How do I loop and store 9 zero's into my "digit" parameter without declaring it as var zr = "000000000"
here's my code:
<html>
<head>
<title>Search</title>
<script>
//This method does the processing
function getInput(input, digit){
var str=input.substring(0,input.length);
var padd0=9-str.length;
var zr="000000000";
var zrsub=zr.substring(0,padd0);
var output="A"+zrsub+""+str;
//can also be var output=input[0]+zrsub+""+str;
return output;
}
//Displays output
function showOutput(){
var input=document.getElementById("search-input").value;
var dislay=document.getElementById("search-output");
dislay.value=getInput(input);
}
</script>
</head>
<body>
<div class="wrapper">
<input type="text" id="search-input">
<input type="button" id="btn" value="ENTER" onclick="showOutput()"> <br><br>
<input type="text" id="search-output">
</div>
</body>
</html>
Sorry just a newbie in this whole programming thing. Just a little confused.
with for loop join string
function joinString(input,digit) {
var inputArr = input.split("");
// var n = 9; // the length of the ouput string;
for (var i = 0; i < digit; i++) {
inputArr.unshift(0);
if (inputArr.length === digit) {
return inputArr.join("");
}
}
}
console.log(joinString("123456"));
You can use padStart
function getInput(input, digit){
return 'A'+ input.toString().padStart(digit, '0');
}
document.getElementById('target').innerHTML = getInput(132,9)
<p id="target"></p>
IE may not support it though.
I have an assignment in school but I'm totally stuck.
My assignment:
Make a program that ask for a text and then write out the text several times. First with just one letter, then with two and so on. For example, if the user write "Thomas", your program should write out "T", "Th, "Tho, "Thom", and so on.
My hopeless attempt
I been trying to use "Substring" and a loop to make it work but I'm not sure I'm on the right path or not. Right now my code look like this:
<head>
<meta charset= "UTF-8"/>
<title> assignment14 - Johan </title>
<script type="text/javascript">
var text= test.length;
for (i=0;i< test.length;i++)
function printit()
{
var str = test;
var res = str.substring (i, 2);
document.getElementById("test").innerHTML = res;
}
</script>
</head>
<body>
<h1>Assignment 14</h1>
<form name="f1">
<input type="text" id="test" value="" />
<input type="button" value="Hämta" onclick="printit(document.getElementById('test'))" />
</form>
</body>
Just need some kind of hint If I'm going in the right direction or not, should I use some other functions? Very thankful for help.
You have to rewrite a script.When you want to extract one by one you can use substring(); function.
How to Call : StringObject.substring (StartPoint,endPoint);
Solution:
<script type="text/javascript">
function printit(){
var test=document.getElementById("test").value;
var text= test.length;
for (i=0;i<= text;i++)
{
var res = test.substring (i, 0);
document.write(res);
document.write("<br/>");
}
}
</script>
You are on the right way. substring(start,end) in javascript gives you the consecutive part of the string letters from start index to end. You just use it in a wrong way for your case. You have to call it like this:
substring(0,i)
You need to make few changes to your code:
1) use document.getElementById('test').value in printit function call at onclick as you have to send the value of the textbox instead of innerHTML.
2) Modify the printif function-
function printit(test)
{
document.getElementById('test').value=''; /*remove existing text from textbox*/
for (i=0;i< test.length;i++) {
var res = str.substring (0, i+1);
document.getElementById("test").value += ' '+res;
}
}
In printit function empty the text box and then append each substring to the existing text to get "T Th Tho Thom.." and so on
Hope this helps.
I don't use for-loop for this (whenever possible, I prefer functional style). Instead, I write a function that returns an array of substrings:
const substrings = string =>
Array.from(string).map((_, i) => string.slice(0, i + 1))
And here's a working codepen
Output several time using substring() method can be done as below, create a function which performs this task of extracting the user inputted string on button click using forloop and substring() method.
var intp = document.querySelector("input");
var btn = document.querySelector("button");
var dv = document.querySelector("div");
btn.onclick = function() {
var b = intp.value;
for (var i = 1; i <= b.length; i++) {
var c = b.substring(0, i);
dv.innerHTML += c + "<br/>";
}
}
div{
width:400px;
background:#111;
color:yellow;
}
<input type="text">
<button>Click</button>
<br/><br/>
<div></div>
You have used a correct way for doing this, but as one of user suggest the start and end value of substring() was not correct.
for learning purpose i'm trying to move an <p> tag innerHTML by one char every second. I managed to move it, but i can't set that delay between moves. It just moves it instantly.
function shiftAChar(str) {
charToShift = str[str.length - 1];
return charToShift + "" + str.substring(0, str.length - 1);
console.log(str);
setTimeout(shiftAChar, 1000);
}
function shiftString(str) {
for (i = 0; i <= 40; i++) {
console.log(str);
str = shiftAChar(str);
document.getElementById("divSecundar").getElementsByTagName("p")[0].innerHTML = str;
}
}
window.onload = function () {
document.getElementById("runEffect").addEventListener("click", function () {
str = document.getElementById("divSecundar").getElementsByTagName("p")[0].innerHTML;
console.log(str);
shiftString(str);
});
document.getElementById("stopEffect").addEventListener("click", function () { run = false; })
}
HTML :
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Nu are</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript" src="evenimente.js"></script>
</head>
<body>
<h2>Header Two</h2>
<div>
<div id="divSecundar">
<p>Aceasta este primul paragraf</p>
<p>Aceasta este al treilea</p>
</div>
<p>Aceasta este cel de-al doilea paragraf</p>
</div>
<input type="text" value="asdf" id="textBoxInput" />
<input type="button" value="Run effect" id="runEffect" />
<input type="button" value="Stop effect" id="stopEffect" />
<input type="button" value="Animatie" id="animatie" />
<br />
<br />
<input type="button" value="Click" id="btnClick" />
<input type="button" value="Click" id="btnClickRemove" />
</body>
</html>
I don't want to use jQuery. Can it be achived using only pure javascript code?
My solution :
function shiftAChar(str) {
charToShift = str[str.length - 1];
return charToShift + "" + str.substring(0, str.length - 1);
}
function shiftString(str, counter) {
if (counter <= 5) {
str = shiftAChar(str);
document.getElementById("divSecundar").getElementsByTagName("p")[0].innerHTML = str;
setTimeout(function () {
shiftString(str, ++counter);
}, 1000);
}
}
window.onload = function () {
document.getElementById("runEffect").addEventListener("click", function () {
str = document.getElementById("divSecundar").getElementsByTagName("p")[0].innerHTML;
console.log(str);
shiftString(str, 0);
});
}
I think you're close. Specifically you don't want to do this in a loop per se, but instead you'd pseudo-recursively call the function using setTimeout (as you're attempting). I think the problem you're finding is that the loop and the setTimeout attempt are both trying to do the same thing, and the loop is simply doing it faster.
For the sake of simplicity, let's assume the logic to move a character from one element to the other is encapsulated in the function moveOneCharacter(). (This would include the actual UI updating.) Since you already know how to make that work, this answer can just focus on the timing problem.
Structurally, the overall process might look something like this:
function shiftTheNextCharacter() {
moveOneCharacter();
if (charactersRemain()) {
setTimeout(shiftTheNextCharacter, 1000);
}
}
No loop needed. Once you call this shiftTheNextCharacter() function, it will move the first character. If there are any more characters (you'd have to write that function too, of course), it schedules itself to shift the next one.
This assumes there's always at least one character to start, of course. You can modify the logic accordingly. But the point of the structure is that a loop will do things instantly, whereas scheduling operations to happen at a later time gives you control over that timing.
This is the full code:
<html>
<head>
<script type='text/javascript'>
var banners = ["Red.jpg","Amber.jpg","Green.jpg"];
var bnrCntr = 0;
var timer;
function banCycle()
{
if(++bnrCntr == 3)
bnrCntr = 0;
document.images.banner.src = banners[bnrCntr];
timer = setTimeout("banCycle()",1000);
}
function stopCycle()
{
clearTimeout(timer);
}
</script>
</head>
<body>
<img src="Red.jpg" name="banner" width=110 height=200>
<form>
<input type="button" value="Cycle" name="Cycle" onclick="banCycle()">
<input type="button" value="Stop" name="Stop" onclick="stopCycle()">
</form>
</body>
</html>
It is the line that I don't understand:
if(++bnrCntr == 3)
Can anyone tell me what this line does?
The line
if (++bnrCntr == 3)
does the same thing as
if ((bnrCntr += 1) == 3)
or
bnrCntr = bnrCntr + 1;
if (bnrCntr == 3)
The value of bnrCntr is incremented, and the result is then assigned back to the variable. Then the value is compared to 3. The ++ operator is called the prefix increment operator.
It first increases the bnrCntr value by 1 and if that value equals to 3 it's set back to 0. You get circular banner changing this way. You could also write it this way, so it's more understandable:
if (++bnrCntr == banners.length)
bnrCntr = 0;
So, when the index goes out of the bounds of the array, start from the beginning.
I am new to programming and am currently stuck on the Ping-Pong aka FizzBuzz problem. (Make a webpage where the user is prompted to enter a number and every number up to that number is displayed. However, for multiples of three, the page prints "ping," for multiples of five, the page prints "pong," and for multiples of both three and five (15), the page prints "ping-pong.")
I've checked out other solutions on here (such as this one) and they've been helpful for understanding how to solve it. And I hope my javascript reflects that.
My problem is I'm stuck trying to take the input number from the form I have on the webpage and run it through the javascript, if that makes sense.
I'm pretty sure that part of my javascript is just a conglomeration of throwing everything I had at it, which is not the best. Could anyone check out my code and see what I'm doing wrong here?
Here's my HTML:
<!DOCTYPE html>
<html>
<head>
<link href="css/bootstrap.css" rel="stylesheet" type="text/css">
<link href="css/styles.css" rel="stylesheet" type="text/css">
<script src="js/jquery-1.11.2.js"></script>
<script src="js/scripts.js"></script>
<title>Ping-Pong Test</title>
</head>
<body>
<div class="container">
<h1>Ping Pong Test</h1>
<p>Let's play the Ping-Pong game. The Ping-Pong game is a simple test that involves loops, conditionals, and variables. Enter your number below to start</p>
<form id="start-form">
<label for="input-number">Your number:</label>
<input id="input-number" type="number">
<button type="submit" class="btn">Calculate</button>
</form>
<div id="end-number">
<ul id="results"></ul>
</div>
</div>
</body>
</html>
And my javascript:
$(document).ready(function () {
$("#start-form").submit(function(event) {
var a = document.getElementById("#input-number");
var num = a.elements[0].value;
var listItems = "";
var i;
for (var i = 1; i <= num; i++) {
if (i % 15 === 0) {
console.log("Ping-Pong");
}
else if (i % 3 === 0) {
console.log("Ping");
}
else if (i % 5 === 0) {
console.log("Pong");
}
else{
console.log(i);
};
event.preventDefault();
};
});
Again, I'm new, so if anyone could break it down step by step, I'd really appreciate it. Thanks.
It is not right:
var a = document.getElementById("#input-number");
Must be one of the below lines:
var a = document.getElementById("input-number");
// Or
var a = $("#input-number").get(0);
// Or
var a = $("#input-number")[0];
But it will not solve your problem. Looking deep into your code. I guess you need to have a form an then get the first element:
var a = document.getElementById("start-form");
var num = a.elements[0].value;
But you can simplify even more. Why not just do it:
// remove the a variable
var num = $("#input-number").val(); // get the input-number value
Based on your code I think you just need some syntax cleaned up in order for jquery to use the value from your form.
I took your code, stripped it down for clarity and made a fiddle out of it.
Here is the link:
http://jsfiddle.net/zwa5s3ao/3/
$(document).ready(function(){
$("form").submit(function(event){
var num = $('#input-number').val()
for (var i = 1; i <= num; i++) {
if (i % 15 === 0) {
$('#list').append('<li>'+"Ping-Pong"+'</li>');}
else if (i % 3 === 0) {
$('#list').append('<li>'+"Ping"+'</li>');}
else if (i % 5 === 0) {
$('#list').append('<li>'+"Pong"+'</li>');}
else{
$('#list').append('<li>'+i+'</li>');}
};
event.preventDefault();
});
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<title>Ping-Pong Test</title>
<body>
<form>
Your number:
<input type="number" name="input-number" id="input-number">
<input type="submit" value="Calculate">
</form>
<ul id="list"></ul>
</body>
Hope this helps!