I am in need of your assistance,
What I need is a javscript function that would accomplish one of two things:
Firstly, if given a string, ie. var x = "filenumber" the function when called, would process the string and add a -2 to the end of it, resulting in var x = "filenumber-2" if the -2 does not exist on the end of the string.
Secondly, if the given value, var x is already = "filenumber-2" then take the number at the end of the string and increment it by 1, resulting in var x = "filenumber-3". and so fourth incrementing the number every single time after that, if the function is called again.
Here is the concept markup:
<DOCYTPE HTML>
<html>
<head>
<script type="text/javascript">
function test(){
var x = document.getElementById('input').value
1.) if x doesnt already have the -2 at the end of the string then add it:
document.getElementById('output').value = x + "-2"
2.) else, the function recognizes that it does and the result of the output is
x-2 + 1
}
</script>
</head>
<body>
<input type="text" id="input"/>
<br>
<input type="text" id="output"/>
<br>
<input type="button" onclick="test()" value="test"/>
</body>
</html>
Short 'n sweet:
x = 'filenumber-4';
x = x.replace(/^(.+?)(-\d+)?$/, function(a,b,c) { return c ? b+(c-1) : a+'-2'; } );
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.
<!DOCTYPE HTML>
<HTML>
<head>
<center>
<b> This is My Virtual Pet!</b>
</center>
<center> <img id="target" src="https://c402277.ssl.cf1.rackcdn.com/photos/14623/images/magazine_hero/WW188829.jpg?1509653431" width="300" height="250" />
<br>
<input type="button" onclick="changeImage()" value=" Scroll Through Emotions" /> </center>
<br>
<center>
<input type="button" onclick="TimeoutStop()" onclick="changeImage(this)" data-values="1,2" value="Feed">
<input type="button" onclick="TimeoutStop()" onclick="changeImage(this)" data-values="3,4,5" value="Pet">
<input type="button" onclick="TimeoutStop()" onclick="changeImage(this)" data-values="3,0,4" value="Play">
</center>
<script>
var target = document.getElementById('target');
var counter = 0;
var myVar;
var myRhino = [
"https://c402277.ssl.cf1.rackcdn.com/photos/14623/images/magazine_hero/WW188829.jpg?1509653431",
"https://img04.deviantart.net/0594/i/2010/261/5/6/happy_rhino_by_ammut88-d2z0sto.jpg",
"https://images.fineartamerica.com/images-medium-large-5/angry-rhino-daniel-eskridge.jpg",
"https://c2.staticflickr.com/2/1340/1368093048_fa7ef85a5a_z.jpg?zz=1",
"https://images.fineartamerica.com/images/artworkimages/mediumlarge/1/hungry-rhino-james-sarjeant.jpg",
"http://m.rgbimg.com/cache1nulfB/users/z/za/zatrokz/600/meRoKDQ.jpg",
"https://i.ytimg.com/vi/R_zz1GEkEk4/maxresdefault.jpg",
];
myVar = setTimeout("TimeoutImg()",2000);
function changeImage(btn) {
if (!btn) {
counter += 1;
target.src = myRhino[counter % myRhino.length];
} else {
var data = btn.getAttribute('data-values');
var pics = JSON.parse("[" + data + "]"); // Convert string of numbers to an array
var num = pics.shift(); // remove index 0 from array and store it in num
pics.push(num); // Add what was previously at index 0 to end of array
target.src = myRhino[num];
counter = num;
btn.setAttribute('data-values', pics.join(','));
}
}
function TimeoutImg(){
target.src = myRhino[6];
}
function TimeoutStop(){
clearTimeout(myVar);
}
</script>
</head>
<body>
</body>
</HTML>
This is the new code with the timeout function. How come when I click the button the timeout stops but It doesn't let me change any pictures on click.
I am trying to have the picture change in 10 seconds after the page opens if no buttons are clicked but if a button is clicked have the timer stop and proceed normallyy by clicked each of the three action buttons and having the image change.
You only need one function to achieve this. Firstly, you can create a function which is in charge of changing the pictures, which you currently have. In my example below I called this changeImage. This function can accept this as an argument, which refers to the current button you clicked on.
onclick="changeImage(this);" // When button is clicked, go to image at index 2
By using this we can get the button's attributes such as the data-values attribute I defined on your buttons.
<input type="button" onclick="changeImage(this)" data-values="1,2" value="Feed">
The data-values attribute allows you to specify the images you want to go to on each image click and the order in which it should follow. I made the data-values attribute work by:
Converting the string value to an array of numbers. Eg: "1,2" turns into [1, 2]. This allows me to manipulate the values easily.
Using this array, I then get the value at index 0 using .shift(). This removes the value at index 0 and also returns it. After using .shift() my array now looks like:
[2].
However, because I used .shift() I was able to store the deleted value in num, which I use as the index for the image to display.
I then use .push() to push the deleted value (or num) back onto the end of my array. So it now looks like [2, 1].
Lastly, I updated the data-values attribute to be equal to this new array. I use .join(',') on the array to turn it into "2,1", and then use .setAttribute to update my data-values attribute. So my element now looks like:
<input type="button" onclick="changeImage(this)" data-values="2,1" value="Feed">
Now, if I click on the button again, I will repeat this cycle, and the image displayed will be 2 and the data-values attribute will be updated to data-values="1,2" again.
However, if a button isn't passed through into the function, (detected by using if(!btn)), then you can simply just change the image based on the counter.
See working example below:
<!DOCTYPE HTML>
<HTML>
<head>
<center>
<b> This is My Virtual Pet!</b>
</center>
<center> <img id="target" src="https://c402277.ssl.cf1.rackcdn.com/photos/14623/images/magazine_hero/WW188829.jpg?1509653431" width="300" height="250" />
<br>
<input type="button" onclick="changeImage()" value=" Scroll Through Emotions" /> </center>
<br>
<center>
<input type="button" onclick="changeImage(this)" data-values="1,2" value="Feed">
<input type="button" onclick="changeImage(this)" data-values="3,4,5" value="Pet">
<input type="button" onclick="changeImage(this)" data-values="3,0,4" value="Play">
</center>
<script>
var target = document.getElementById('target');
var counter = 0;
var myRhino = [
"https://c402277.ssl.cf1.rackcdn.com/photos/14623/images/magazine_hero/WW188829.jpg?1509653431",
"https://img04.deviantart.net/0594/i/2010/261/5/6/happy_rhino_by_ammut88-d2z0sto.jpg",
"https://images.fineartamerica.com/images-medium-large-5/angry-rhino-daniel-eskridge.jpg",
"https://c2.staticflickr.com/2/1340/1368093048_fa7ef85a5a_z.jpg?zz=1",
"https://images.fineartamerica.com/images/artworkimages/mediumlarge/1/hungry-rhino-james-sarjeant.jpg",
"http://m.rgbimg.com/cache1nulfB/users/z/za/zatrokz/600/meRoKDQ.jpg",
"https://i.ytimg.com/vi/R_zz1GEkEk4/maxresdefault.jpg",
];
function changeImage(btn) {
if (!btn) {
counter += 1;
target.src = myRhino[counter % myRhino.length];
} else {
var data = btn.getAttribute('data-values');
var pics = JSON.parse("[" + data + "]"); // Convert string of numbers to an array
var num = pics.shift(); // remove index 0 from array and store it in num
pics.push(num); // Add what was previously at index 0 to end of array
target.src = myRhino[num];
counter = num;
btn.setAttribute('data-values', pics.join(','));
}
}
</script>
</head>
<body>
</body>
</HTML>
As you've edited your question to a new question, I'll post an additional answer.
The reason as to why your timer isn't working is because you have a few issues with your code:
myVar = setTimeout("TimeoutImg()",2000); isn't correct, your first argument for setTimeout should be a function callback, not a string. Here you've almost got it right, you just need to change your string to the function callback:
var myVar = setTimeout(TimeoutImg, 2000);
Also, generally in programming, it's not considered "good practice" to name your functions with capital letters at the start (as you use capitals for classes/objects). So from now on, I will use lowercase letters at the start of each function name.
Another issue is how you are stopping the timeout interval. You've
got the right idea with having onlcick trigger the timeoutStop
function, however, you're not going about it the right way. A HTML
element should only have no repeated attributes on it, so in your
case, you're repeating onclick twice:
onclick="timeoutStop()" onclick="changeImage(this)"
Instead, of having two onclick attributes, you can combine these into one:
onclick="changeImage(this); timeoutStop()"
Fixing these issues will resolve your issue.
See working example below:
<!DOCTYPE HTML>
<HTML>
<head>
<center>
<b> This is My Virtual Pet!</b>
</center>
<center> <img id="target" src="https://c402277.ssl.cf1.rackcdn.com/photos/14623/images/magazine_hero/WW188829.jpg?1509653431" width="300" height="250" />
<br>
<input type="button" onclick="changeImage()" value=" Scroll Through Emotions" /> </center>
<br>
<center>
<input type="button" onclick="changeImage(this); timeoutStop()" data-values="1,2" value="Feed">
<input type="button" onclick="changeImage(this); timeoutStop()" data-values="3,4,5" value="Pet">
<input type="button" onclick="changeImage(this); timeoutStop()" data-values="3,0,4" value="Play">
</center>
<script>
var target = document.getElementById('target');
var counter = 0;
var myRhino = [
"https://c402277.ssl.cf1.rackcdn.com/photos/14623/images/magazine_hero/WW188829.jpg?1509653431",
"https://img04.deviantart.net/0594/i/2010/261/5/6/happy_rhino_by_ammut88-d2z0sto.jpg",
"https://images.fineartamerica.com/images-medium-large-5/angry-rhino-daniel-eskridge.jpg",
"https://c2.staticflickr.com/2/1340/1368093048_fa7ef85a5a_z.jpg?zz=1",
"https://images.fineartamerica.com/images/artworkimages/mediumlarge/1/hungry-rhino-james-sarjeant.jpg",
"http://m.rgbimg.com/cache1nulfB/users/z/za/zatrokz/600/meRoKDQ.jpg",
"https://i.ytimg.com/vi/R_zz1GEkEk4/maxresdefault.jpg",
];
var changeImageTimer = setTimeout(timeoutImg, 5000); // 5 second timer
function changeImage(btn) {
if (!btn) {
counter += 1;
target.src = myRhino[counter % myRhino.length];
} else {
var data = btn.getAttribute('data-values');
var pics = JSON.parse("[" + data + "]"); // Convert string of numbers to an array
var num = pics.shift(); // remove index 0 from array and store it in num
pics.push(num); // Add what was previously at index 0 to end of array
target.src = myRhino[num];
counter = num;
btn.setAttribute('data-values', pics.join(','));
}
}
function timeoutImg() {
target.src = myRhino[myRhino.length-1];
}
function timeoutStop() {
clearTimeout(changeImageTimer);
}
</script>
</head>
<body>
</body>
</HTML>
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.
This script is supposed to take a list of links, transform some by changing some words and eliminate others containing specific string of characters.
The first part is ok. I need help with the second. The line
x = x.replace(/^.+/category/.+$/mg, "");
doesn't work even if we change the + with *. I used sources from here (1 & 2 ). So, help the noob.
<!DOCTYPE html>
<html>
<body>
<h3>Instert your links</h3>
input:<br>
<textarea id="myTextarea">
http://example.com/ad/123.html
http://example.com/ad/345.html
http://example.com/ad/3567.html
http://example.com/category/fashion.html
http://example.com/ad/8910.html
http://example.com/category/sports.html
</textarea>
<button type="button" onclick="myFunction()">Get clean links</button>
<p id="links"></p>
<script>
function myFunction() {
x = document.getElementById("myTextarea").value;
x = x.replace(/http:\/\/example.com\/ad\//g, "http://example./com/story/");
x = x.replace(/\n/g,"</br>");
x = x.replace(/^.+/category/.+$/mg, "");
document.getElementById("links").innerHTML = x;
}
</script>
</body>
</html>
I think you need to escape your forward slashes as you are also using them as the regex delimiter.
x = x.replace(/^.+\/category\/.+$/mg, "");
Assuming that you want to copy those lines in <p> remove line containing category in it.
change your function to
function myFunction() {
x = document.getElementById("myTextarea").value;
var lines = x.split("\n").filter( function(val){
return val.indexOf( "category" ) == -1;
});
document.getElementById("links").innerHTML = lines.join( "<br>" );
}
Very new to html and javascript here. I get the following form up and it calculates correctly but the result shows up in a new page. I'd like it to stay in the same page. Not sure what I did wrong here. Also, is there any way to shorten the function? Seems like a lot of work to do a simple calculation. Any help would be great.
<html>
<head>
<title>Help!</help>
<script type="text/javascript">
function add(x,y){
var x = document.add1.add2.value;
var y = document.add1.add3.value;
var x = Number(x);
var y = Number(y);
var z = x+y;
return (z);
}
</script>
</head>
<body>
<h3>Help me stack overflow you're my only hope!</h3>
<form name="add1">
Input first number to add: <input type="number" name="add2">
2nd number: <input type="number" name="add3">
<input type="button" value="Result"
onclick = "document.write('The total is: ' + add() + '.');" />
</body>
</html>
Dont' use document.write to display data, it overwrites entire document. You don't want that. It's better to create new function which would render result into some other element:
<input type="button" value="Result" onclick="showResult('The total is: ' + add() + '.');" />
and the showResult function can be for example:
function showResult(result) {
document.getElementById('result').innerHTML = result;
}
HTML:
<div id="result"></div>
Demo: http://jsfiddle.net/7ujzn35c/
Here are also a couple of general improvements you can make your code:
move string manupulations to showResult completely:
<input type="button" value="Result" onclick="showResult()" />
http://jsfiddle.net/7ujzn35c/1/
call add from inside showResults
onclick="showResult(this.form.add2.value, this.form.add3.value)"
http://jsfiddle.net/7ujzn35c/2/
<title>Help!</help>
First of all, This should be <title> Help! </title>
Secondly, document.write function actually starts writing the entire page anew.
You should either replace onclick = "document.write('The total is: ' + add() + '.');" with
onclick = "alert('The total is: ' + add() + '.');"
Better still, you could create a div element like so
<title> Help! </title>
<script>
.....
</script>
</header>
<body>
<div id = 'output'> </div> ...
then
`onclick = "document.getElementById("output").innerHTML = 'The total is: ' + add() + '.';"
And don't give up. Hope this helps you