Form button keeps showing results in new window - javascript

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

Related

Uncaught TypeError from generated JavaScript elements

I'm generating a dynamic list of from/inputs and buttons from JSON. The button triggers a JavaScript function that reads the current content of the input in a form. However when the button is clicked I get the following error code Uncaught TypeError: Cannot read property '0' of undefined.
This tells me there are no elements in the form but I don't know why. Tryed 0-3 just to make sure.
Length also return undefined. I am able to edit the innerHTML of the form.
A striped down code I'm trying to get a value from.
<!DOCTYPE html>
<html>
<body onload="gen_form()">
<div id="connectResult"></div>
<p id="demo">RESULT HERE</p>
<script>
const connect_result = document.getElementById("connectResult");
function gen_form(){
var div = document.createElement("DIV");
div.setAttribute("id", "div0");
div.innerHTML += "sometxt<br/>";
var form1 = document.createElement("FROM");
form1.setAttribute("id", 'form_sometxt2_0');
var input1 = document.createElement("input");
input1.setAttribute("type",'text');
input1.setAttribute("name",'textbox');
form1.appendChild(input1);
div.appendChild(form1);
var btn4 = document.createElement("BUTTON");
btn4.setAttribute("id", 'WRITE_sometxt2_0');
btn4.innerHTML = 'WRITE';
btn4.setAttribute("onclick", "myFunction(this)");
div.appendChild(btn4);
connect_result.appendChild(div);
}
function myFunction(param) {
var text = document.getElementById("form_sometxt2_0").elements[0].value + "<br>";
document.getElementById("demo").innerHTML = text;
}
</script>
</html>
The following does exactly what I want but it is static. The above is based off this.
<!DOCTYPE html>
<html>
<body>
<form id="frm1">
<input type="text">
</form>
<button onclick="myFunction()">Try it</button>
<p id="demo">RESULT HERE</p>
<script>
function myFunction() {
var text = document.getElementById("frm1").elements[0].value + "<br>";
document.getElementById("demo").innerHTML = text;
}
</script>
</html>
My question is: What is the difference between these two code snippets and how do I fix said error?
I would prefer not to use a submit input as there will be a second button that edits the contents of the input value.
PS: I'm fairly new to JavaScript and its terminology.
Using Chrome as my debugger.
Tipo error.comment
var form1 = document.createElement("FROM");
should be:
var form1 = document.createElement("FORM");

Javascript Function to setTimeout and when a button on page is clicked cancel the timeout and proceed with the remaining functions?

<!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>

How to insert an ID from an HTML document into a VAR function in JavaScript?

Im trying to make an 'online' (HTML document) file that has an input to solve math, and I need a way to type in the numbers, and insert a 'solve me' button. I have the button, and the form by ID and class as well.
This is what I inserted into a "try it" prompt box through w3schools.com site, tried looking almost everywhere within that site to try to input it in.
<div id="A"></div>
<div id="B"></div>
<script>
var A = 1;
var ele = document.getElementById('A');
var y = 2;
var z = A + y;
document.getElementById("demo").innerHTML = z;
</script>
Is there a way to do this? And thank you guys for your help!
<!DOCTYPE html>
<html>
<body>
<input id="A"/>
<input id="B"/>
<div id="demo"></div>
<button onclick="add();">ADD</button>
<script>
function add () {
var A = document.getElementById('A').value *1;
var B = document.getElementById('B').value *1;
var z = A + B;
document.getElementById("demo").innerHTML = z;
}
</script>
</body>
</html>
Hope this helps you, here you need to use input to have a user editable field,a div as you guessed to display your answer and button which triggers some logic.

Modifying the integer at the end of a string

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'; } );

Javascript - Cannot get function to set global variable to be used outside function

I'm attempting to make a simple linear text game that will display inside a div on a webpage. I am using innerHTML to write the contents of the game to the div, and using onclick from a button to change the contents. My problem is that I would also like to include a few user-submitted variables, which I am trying to do using prompt() inside a function.
The problem is, I can't get the variable to set globally. It works when called inside the function, but nowhere else.
I've tried declaring the variable first outside the function, using window.variable (both inside and outside of the function) as well as leaving off the var before the variable inside the function to make it global in scope.
I have looked for solutions and nothing seems to work! Am I missing something with the order of my script?
Here is the javascript:
var cb2 = '<input id="button" type="button" value="Continue" onclick="replace(\'gamebox\',next3,\'continueBttn\',cb3);">';
var cb3 = '<input id="button" type="button" value="Continue" onclick="getName();">';
var cb4 = '<input id="button" type="button" value="Continue" onclick="replace(\'gamebox\',next5,\'continueBttn\',cb5);">';
var cb5 = '<input id="button" type="button" value="Continue" onclick="replace(\'gamebox\',next6,\'continueBttn\',cb6);">';
var testName = "Test Name";
var player1;
var next2 = "<p>Great, you've certainly got an adventurer's spirit! Now I just need a few details about you and your party.</p>";
var next3 = "<p>First, I'd like to get everyone's name</p>"
var next4 = "<p>Thanks " + testName + "!</p>"
var next5 = "<p>Now you're ready " + player1 + "! Click to set out on the trail!</p>"
var continueButton = function (content) {
document.getElementById('continueBttn').innerHTML = content;
};
function replace(id1,content,id2,cb) {
document.getElementById(id1).innerHTML = content;
document.getElementById(id2).innerHTML = cb;
}
function getName() {
player1 = prompt("What is your Name?");
alert("Your name is " + player1 + ".");
replace('gamebox',next4,'continueBttn',cb4);
}
And here is the html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="oregon.css" />
</head>
<body>
<div id="gameContainer">
<div id="gamebox">
<p>Welcome to the Oregon Trail! Click Continue to travel the trail!</p>
</div>
</div>
<div id="continueBttn"><input id="button" type="button" value="Continue" onclick="replace('gamebox',next2,'continueBttn',cb2);"></div>
</body>
</html>
<script src="oregon.js" type="text/javascript"></script>
Ok, I got your stuff to work. Take the var off of the variables to make them global and change your functions to be assigned to a variable like continueButton:
replace = function(id1, content, id2, cb) {
document.getElementById(id1).innerHTML = content;
document.getElementById(id2).innerHTML = cb;
}
getName = function() {
player1 = prompt("What is your Name?");
alert("Your name is " + player1 + ".");
replace('gamebox', next4, 'continueBttn', cb4);
}
This got things working for me.
The other answers here have good points as well, you need a better way of handling the player name.
player1 is used into the expression next5, not next4 (which is the one of your getName() function)
Anyway, it will never work like this. At the moment next5 is initialized the value of player1 was defined a certain way, and will remain defined that way unless you redefine the next5 variable again.
You need to encapsulate the next5 definition into a function in order to make it dynamic.
Problem is here
var next5 = "<p>Now you're ready " + player1 + "! Click to set out on the trail!</p>"
It uses the variable when it is first rendered, it will not be updated when you set player1 to a new value.
You need to figure out a different way to set the player's name. One way of doing it is to replace it.
var next5 = "<p>Now you're ready {player1}! Click to set out on the trail!</p>"
and when you use it
var newStr = next5.replace("{player1}", player1);

Categories

Resources