I'm trying to get answer to display when I press the Show Button but I can't get it to work. Could someone help me understand what I am doing wrong. I can get the first part to work where I generate a random integer. But the second part does not execute (JSFiddle).
<!DOCTYPE html>
<html>
<body>
<button class="button" onclick="disp()">Generate</button>
<button class="button" onclick="show_ans()">Show</button>
<script>
function disp() {
var i = Math.floor((Math.random() * 51) + 1);
var j = 2 * i;
document.getElementById("Goal").innerHTML = [i];
function show_ans() {
document.getElementById("answer").innerHTML = [j];
}
}
</script>
<p> Random Integer:
<span id="Goal"></span>
</p>
<p> Computed Answer:
<span id="answer"></span>
</p>
</body>
</html>
show_ans only exists within the scope of the disp function, so anything outside that scope (such as the rest of the page) can't invoke it.
Move it outside that function:
function disp() {
//...
}
function show_ans() {
//...
}
Of course, since show_ans also relies on j, that too will need to exist in a scope where both functions can access it:
var j;
function disp() {
var i = Math.floor((Math.random() * 51) + 1);
j = 2 * i;
document.getElementById("Goal").innerHTML = [i];
}
function show_ans() {
document.getElementById("answer").innerHTML = [j];
}
Related
I'm very new to JavaScript so I apologize if this question has an extremely obvious answer. What I'm trying to do is pass the name of a text box in HTML to a function in Javascript via an onclick button. The goal of the function is to test a given string and highlight it based on certain parameters (for my testing, it is simply length).
There are multiple weird odds and ends within the functions that I'm aware of and working on, I know the functions work as when I remove the parameters and call the code text box directly, it prints exactly what I expect it to. But I want to be able to pass multiple text boxes without needing a specific function per box.
The code I have is as follows. I've included all of it in case the mistake was made somewhere I didn't expect it to be.
<!DOCTYPE html>
<html>
<head>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<label for="wordOne">Word One</label><br>
<input type="text" id="wordOne" name="wordOne"><br>
// Pass the value for the wordOne textbox to verify function
<button type="button" onclick="verify(wordOne,this)">Check</button><br><br>
<label for="wordTwo">Word Two</label><br>
<input type="text" id="wordTwo" name="wordTwo"><br>
// Pass the value for the wordTwo textbox to verify function
<button type="button" onclick="verify(wordTwo,this)">Check</button><br><br>
<p id="test"></p><br>
<p id="error"></p>
<script>
// Highlights any code in a given line.
function highlight(text,id,begin,end) {
// document.getElementById("error").innerHTML = "TEST";
var inputText = document.getElementById(id);
var innerHTML = inputText.innerHTML;
var index = innerHTML.indexOf(text)+begin;
if (index >= 0) {
innerHTML = innerHTML.substring(0,index) + "<span class='highlight'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length-end);
inputText.innerHTML = innerHTML;
return string;
}
}
function verify(button,el){
var begin=1;
var end=1
var id="test";
var string = document.getElementById(button).value;
var len=string.length;
if(len>5)
{
document.getElementById(id).innerHTML = string +" "+len;
highlight(string,id,begin,end);
}
else
{
document.getElementById(id).innerHTML = string;
}
}
</script>
</body>
</html>
I apologize again if this is extremely obvious but I'm honestly not sure what I'm doing wrong. Thanks in advance for any help!
You can get the name of the textbox by the attribute
var x = document.getElementsByTagName("INPUT")[0].getAttribute("name");
And then use it in your function as
var x = document.getElementsByTagName("INPUT")[0].getAttribute("name");
function highlight(x,id,begin,end) {
// document.getElementById("error").innerHTML = "TEST";
var inputText = document.getElementById(id);
var innerHTML = inputText.innerHTML;
var index = innerHTML.indexOf(text)+begin;
if (index >= 0) {
innerHTML = innerHTML.substring(0,index) + "<span class='highlight'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length-end);
inputText.innerHTML = innerHTML;
return string;
}
}
NOTE : By [0] it means the first one that is the first textbox.
I want to make a page with JavaScript that has a button saying "Multiplication Tables." When I click the button, the multiplication table of 5 will show up in the "p" tag with the id "tables." I want to use a for loop to calculate the tables. Nothing is happening when I click the button.
HTML:
<body>
<button type="button" id="multiplication" onclick="table()">Multiplication Tables</button>
<br/>
<p id="tables"></p>
</body>
</html>
JavaScript:
function table()
{
var button = document.getElementById('multiplication');
var showTables = '';
for (var i=1; i<12; i++) {
showTables += 5 + "*" + i +"="+5*i + '\n';
}
var p_tables = document.getElementById('tables').innerHTML = showTables;
}
table();
Check this snippet by clicking run snippet button below, I think it's working fine
function table()
{
var button = document.getElementById('multiplication');
var showTables = '';
for (var i=1; i<12; i++) {
showTables += 5 + "*" + i +"="+5*i + '\n';
}
var p_tables = document.getElementById('tables').innerHTML = showTables;
}
<html>
<body>
<button type="button" id="multiplication" onclick="table()">Multiplication Tables</button>
<br/>
<p id="tables"></p>
</body>
</html>
Your are missing html tag before body and there might be some problem with your javascript inclusion, Also don't run table() function after declaring it.
Place the script either in head tag or before closing the body. Remove table() function calling after declaring it.
I have 6 buttons on the top of my page where the first one is working. When pressing a button I need it to dynamically change the "function name" in my script to match the button "function name". Also for each button I need "tr.cells" to increase +1 which is the next column of my table.
Basically what all this does; my table is 50 Rows 10 Columns that the code looks through for the word "none" if it finds "none" then lines I ID'ed in my document will be hidden.
I have done a hours of research but I am unable get anything to work with my code. I gave an example of what I tried to incorporate but I was unsuccessful. Need it to work with my buttons. I greatly appreciate any help anyone can give. Thank you.
Example Idea
function F1() { };
function F2() { };
var myFunctions = [F1, F2];
r nextFunction = 0;
function myFunctionSwitcher() {
myFunctions[nextFunction]();
nextFunction = nextFunction + 1;
My Code
<td><div align="center"><button onclick = "F1()"> 178-0000-00 </button></div></td>
<td><div align="center"><button onclick = "F2()"> 178-0001-00 </button></div></td>
<script type="text/javascript">
function F1() /*Change this for "Board Number" #*/
/*Start Loop*/{
var tab = document.getElementById('part1Table');
var l = tab.rows.length;
for ( var i = 0; i < l; i++ ) {
var tr = tab.rows[i];
var cll = tr.cells[2];
if(s = cll.innerText.indexOf('None') != -1)
{
var Z = ("")
jQuery(function($)
{
$('#resultA').load('DocText.html #Tablemain1');
});;
/* Start Copy */
if (i==1) /*Change this for "Line in ABI Doc" */
{ var e = document.getElementById('result1'); /*Change this for "Line Hidden" */
e.style.display = 'none';}
/* End Copy */
}}} </script>
http://jsfiddle.net/4SB25/
HTML:
<button onclick="func(1)">Button No. 1</button><br>
<button onclick="func(2)">Button No. 2</button><br>
<button onclick="func(3)">Button No. 3</button><br>
<button onclick="func(4)">Button No. 4</button><br>
<button onclick="func(5)">Button No. 5</button><br>
<button onclick="func(6)">Button No. 6</button><br>
<div id="results"></div>
JAVASCRIPT:
var counter = 1;
function func(id) {
if (id != counter)
return;
document.getElementById('results').innerHTML+="Button No. "+id+" was pressed<br>";
counter++;
}
You can use the same logic for the cell number. You set it globally (like the counter variable) with the value of the first cell, and when you update the counter you can update this variable as well.
<!DOCTYPE HTML>
<html>
<head>
<title>Zautra Levels</title>
<h2 style="font-family: Trebuchet MS; color: blue;"">Zautra Levels</h2>
<p> </p>
</head>
<body>
<p>Clickables:</p>
<button id="swag" onclick="lmao()">Gain XP</button> <button id="gold" onclick="getgold()">Get Gold</button> <button id="buyupgrade" onclick="buyupp()">Level Up!</button>
<p> </p>
<div id="total">XP: 0</div>
<div id="goldt">Gold: 0</div>
<div id="upgradess">Level: 0</div>
<div id="upcostt">Required XP: 25</div>
<script>
var clicks = 0; // How many clicks you have
var upgrades = 0; // How many upgrades you have purchased
var upcost = 25; // How much the upgrades cost
var gold = 0; // How much gold you have
function updateclicks() { // Declares the function that updates the "Zautra Clicks" Text.
var v=document.getElementById("total");
v.innerHTML = 'XP: ' + clicks;
}
function updategold() { // Declares the function that updates the "Zautra Clicks" Text.
var g=document.getElementById("goldt");
g.innerHTML = 'Gold: ' + gold;
}
function updateupgradecounter() { // Declares the function that updates the "Upgrades:" Text.
var y=document.getElementById("upgradess");
y.innerHTML = 'Level: ' + upgrades;
}
function updateupcost() { // Declares the function that updates the "Upgrade Cost:" Text.
var z=document.getElementById("upcostt");
z.innerHTML = 'Required XP:' + upcost;
}
var x=document.getElementById("swag"); function lmao() { // When you click the "Click for MOAR Zautra's" Button you get a +1 Click.
clicks+=1;
updateclicks();
}
var j=document.getElementById("gold"); function getgold() { // When you click the "Click for MOAR Zautra's" Button you get a +1 Click.
gold+=1;
updategold();
}
var c=document.getElementById("buyupgrade"); function buyupp() {
if (clicks >= upcost) {
clicks-=upcost
upgrades+=1
upcost*=2
updateclicks();
updateupgradecounter();
updateupcost();
}
else
{
var clicksdif = upcost - clicks;
confirm("You need " + clicksdif + " more XP to level up.");
}
}
</script>
</body>
</html>
This is the code for my game that I am working on.
I'm trying to add a button, and when you press it, it saves all of the variables.
If you're level 5 with 26 XP, and 7 gold, you refresh the page, you still have those stats instead of losing them on refresh.
Please help!
(And yeah, I do realize that the code is really messed up, but that is a small issue. I'll fix that sooner or later.)
I believe that actually the easiest way, easier than cookies, is to pass the values via the URL. Example:
<form action="yourPage.php?gold=$amount&level=$whatlevel&experience=$experience" method="POST">
//Your refresh button here
</form>
and then to retrieve those variables when the page reloads, use: gold=$_POST['gold']
Another option as well is to use the GET method instead of POST.
Keep in mind that the file extension needs to be php for this code to work.
you could create a cookie in php:
setcookie("NameOfTheCookie",$value,$expireTime)
and $value can be an array of values as well.
I trying to generate an input (type="button") and setting the onclick-Event to a function, which should hand over a parameter. The whole object should be appended to a div and thats it. Basically this is my try, but I can't see why it does not work.
I pasted the code to jsfiddle, hence its easier for you to reproduce. Click here.
What am I'm doing wrong? I'm learning it by trial and error, so please explain whats wrong. Thanks a lot!
[edit] for the case jsfiddle will be down one day, here is the code I tried to run... :)
<!doctype html>
<html>
<head>
<title>onclick event example</title>
<script type="text/javascript" language="javascript">
var i = 0;
var h = new Array();
function addButton() {
i++;
var container = document.getElementById("check0");
var h[i] = document.createElement("input");
h[i].type = 'button';
h[i].name = 'number' + i;
h[i].value = "number" + i;
h[i].id = 'number' + i;
h[i].onclick = function() {
showAlert(i)
};
container.appendChild(h[i]);
}
function showAlert(number) {
alert("You clicked Button " + number);
}
</script>
</head>
<body>
<div id="check0">
<input type="button" value="klick mich" id="number0" onclick="addButton()"/>
</div>
</body>
</html>
Here is the fixed fiddle for you.
var h[i] = ... is invalid JavaScript.
What you write in the "JavaScript" frame on jsfiddle is executed onload, so this code is not yet present when the HTML you provide is executed (and neither is the addButton() function).
<script>
var i = 0;
var h = new Array();
function addButton() {
i++;
var container = document.getElementById("check0");
h[i] = document.createElement("input");
h[i].type = 'button';
h[i].name = 'number' + i;
h[i].value = "number" + i;
h[i].id = 'number' + i;
h[i].onclick = function() {
showAlert(i)
};
container.appendChild(h[i]);
}
function showAlert(number) {
alert("You clicked Button " + number);
}
</script>
<div id="check0">
<input type="button" value="klick mich" id="number0" onclick="addButton()"/>
</div>
Try using h.push(...) instead of trying to send to a non created element in the array
var x = document.getElementById('pagination');//pagination is an empty div in html
var y ='';
for(var i = 0; i <= (pageMax); i++){
y = y+"<a id ='pageNumber"+i+"' onclick='changePage("+(i+1)+");'>"+(i+1)+"</a>\n ";
} x.innerHTML=y }
i used this to make a pagination for a table. The function will create a row of numbers until button max. 'changePage("+(i+1)+"); ... will call a function and send the i index(number that the page is) of the pagenumber. also i dynamically create a id unique for each number.