Jump to content

Putting the result of a function into the document as text


Sansespere

Recommended Posts

Hi. I've been having a problem making a function in the head of the document to be executed on the click of a link, and then for the result of my function to be displayed after that link, in this case a <span> tag I made. Any help would be appreciated. My code looks like this:

<html><head><script type="text/javascript">function generateint(){var i20=(Math.floor(Math.random()*20) + 1);document.getElementById("show").innerHTML = i20;/* I want this function to stay permanent. I have seen the number come up for a split second, but it then resets back to 0. I want it to generate a new number each time the link (or whatever i choose) is pressed, and then for that number to stay there until the link is pressed again. (and not just any link on the page refreshing it, like i had at one point got it to do but never found out how to get back. */}</script></head><body><a href="" onclick="generateint()">generate integer:</a><span> <span id="show"></span></span></body></html>

Thanks,Eru

Link to comment
Share on other sites

<u onclick="generateint()">generate integer:</u><span> <span id="show"></span></span>
That did not work. but thanks for your input. I think there may be a problem with my javascript in my function. Anybody else see anything?
Link to comment
Share on other sites

By leaving the href attribute blank, the browser is reopening the page after you click on the link. Try this:<a href="#" onclick="generateint(); return false">generate integer:</a>

Link to comment
Share on other sites

By leaving the href attribute blank, the browser is reopening the page after you click on the link. Try this:<a href="#" onclick="generateint(); return false">generate integer:</a>
That worked Ingolme! Thank-you very much!!! May I ask what the purpose of the return false is if you say it was the empty href causing the problem and what the # does inside the href? I read somewhere about javascript void(0) but that didn't work. This way I can learn and solve things myself in the future.Thanks,Eru
Link to comment
Share on other sites

return false will stop the link from performing its default action (opening a page in the browser window).Having an href attribute makes the link load another page. If the href attribute is an empty string the loaded page will be the current one, it's as good as refreshing the page: any changes done by Javascript will be reset.

Link to comment
Share on other sites

Actually, now my problem has come back on another page I am using the same script. Here is my old one copied exactly as i have it:

<html><head><link rel="stylesheet" type="text/css" href="MyD&Dstyles.css" /><script type="text/javascript">function rolld20(){var d20=(Math.floor(Math.random()*20) + 1);document.getElementById("showd20").innerHTML = d20;}function rolld12(){var d12=(Math.floor(Math.random()*12) + 1);document.getElementById("showd12").innerHTML = d12}</script></head><body class="bar"><h3>-=Actions=-</h3><a href="" onclick="rolld20(); return false">Roll 1-20:</a><span> <span id="showd20"></span></span><br /><u onclick="rolld12()">Roll 1-12:</u><span> <span id="showd12"></span></span><br /></body></html>

Both <a> and <u> tag work perfectly. Now here is my current page copied exactly as i have it:

<html><head><title>Dungeons & Dragons - My Dice Roller</title><link rel="stylesheet" type="text/css" href="MyD&Dstyles.css" /><script src="roller.js"></script></head><body class="bar"> <h4>Roll a single die of one type by clicking on the die name</h4>  <a href="" onclick="rolld20(); return false">Roll a d20</a> <span id="d20result">0</span><br /> <span class="diceside" id="d12result"></span><a title="Twelve-sided die" href="" onclick="rolld12(); return false">Roll a d12</a><br /> <span class="diceside" id="d10result"></span><a title="Ten-sided die" href="#" onclick="rolld10(); return false">Roll a d10</a><br /> <span class="diceside" id="d%result"></span><a title="Percentile die (1-100%)" href="" onclick="rolld%(); return false">Roll a d%</a><br /> <span class="diceside" id="d8result"></span><a title="Eight-sided die" href="" onclick="rolld8(); return false">Roll a d8</a><br /> <span class="diceside" id="d6result"></span><a title="Six-sided die" href="" onclick="rolld6(); return false">Roll a d6</a><br /> <span class="diceside" id="d4result"></span><a title="Four-sided die" href="" onclick="rolld4(); return false">Roll a d4</a><br /> <span class="diceside" id="d3result"></span><a title='"Three-sided die" Normally impossible in real life' href="" onclick="rolld3(); return false">Roll a d3</a><br /> <span class="diceside" id="d2result"></span><a title='"Two-sided die" Or a coin in real life' href="" onclick="rolld2(); return false">Roll a d2</a> ...</body></html>

with the attached javascript file:

function rolld20(){var d20=(Math.floor(Math.random()*20) + 1);document.getElementById("d20result").innerHTML = d20;}function rolld12(){var d12=(Math.floor(Math.random()*12) + 1);document.getElementById("d12result").innerHTML = d12;}function rolld10(){var d10=(Math.floor(Math.random()*10) + 1);document.getElementById("d10result").innerHTML = d10;}function rolld%(){var d%=(Math.floor(Math.random()*100) + 1);document.getElementById("d%result").innerHTML = d%;}...

I don't see a difference in theory do you?

Link to comment
Share on other sites

Hi, why don't you put all your functions in only one, something like:function rolld(sides){ var d=(Math.floor(Math.random()*Number(sides)) + 1); document.getElementById("d"+ sides +"result").innerHTML = d;}calling it onclick="rolld(20)" onclick="rolld(12)" onclick="rolld(100)" //the number doesn't bother etc.

Link to comment
Share on other sites

Hi, why don't you put all your functions in only one, something like:function rolld(sides){ var d=(Math.floor(Math.random()*Number(sides)) + 1); document.getElementById("d"+ sides +"result").innerHTML = d;}calling it onclick="rolld(20)" onclick="rolld(12)" onclick="rolld(100)" //the number doesn't bother etc.
Hey thanks, that is a great idea! It works now but, may I ask if anyone knows why the other one wasn't working? Do you think there were just too many functions or too many functions named rolld...?
Link to comment
Share on other sites

This is more or less the guts of what you want. Learn from it. :)

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"   "http://www.w3.org/TR/html4/strict.dtd"><html>	<head>		<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">		<title></title>		<script type="text/javascript">			function init () {				var links = document.getElementsByTagName("a");				for (var i = 0; links[i]; i++) {					links[i].onclick = function () {						var sides = this.id.match(/[0-9]+$/)						alert (sides);						return false;					}				}			}			window.onload = init;		</script>	</head>	<body>		<div>			<a href="#" id="d1">1</a><br>			<a href="#" id="d2">2</a><br>			<a href="#" id="d3">3</a><br>			<a href="#" id="d4">4</a><br>			<a href="#" id="d5">5</a><br>			<a href="#" id="d6">6</a><br>			<a href="#" id="d7">7</a><br>		</div>	</body></html>

Link to comment
Share on other sites

This is more or less the guts of what you want. Learn from it. :)
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"   "http://www.w3.org/TR/html4/strict.dtd"><html>	<head>		<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">		<title></title>		<script type="text/javascript">			function init () {				var links = document.getElementsByTagName("a");				for (var i = 0; links[i]; i++) {					links[i].onclick = function () {						var sides = this.id.match(/[0-9]+$/)						alert (sides);						return false;					}				}			}			window.onload = init;		</script>	</head>	<body>		<div>			<a href="#" id="d1">1</a><br>			<a href="#" id="d2">2</a><br>			<a href="#" id="d3">3</a><br>			<a href="#" id="d4">4</a><br>			<a href="#" id="d5">5</a><br>			<a href="#" id="d6">6</a><br>			<a href="#" id="d7">7</a><br>		</div>	</body></html>

OK I might need some explination as to what this all does. I will try to figure most of it out for myself.
function init () { // this line makes the function but is init a custom name or a previously created function?		var links = document.getElementsByTagName("a"); // this says that the variable links refers to all the <a> tags?? but what does that do?		for (var i = 0; links[i]; i++) { //This starts a loop that I don't understand			links[i].onclick = function () { 				var sides = this.id.match(/[0-9]+$/) //Where did the math go? Maybe there is some online literature I can read ???				alert (sides);					return false;			}		}	}window.onload = init;

I'm sorry I don't know so much and I'm just a newb, but I really am trying to learn! and I appreciate everyone who has given me input here. Thank you all a ton!Eru

Link to comment
Share on other sites

OK I might need some explination as to what this all does. I will try to figure most of it out for myself.
Mostly, it simplifies things. You don't need a separate function for each kind of dice. You don't need to write a special onclick handler for every <a> tag. All you have to do is create <a> tags that have an id property. The id must begin with the letter "d" and be followed by the number of sides for that die. So a four-sided die has id="d4".That's pretty easy.The function does this: it goes out and finds every <a> tag on your page. (If that's too many, let me know and we can easily fix that.) The function now adds a unique onclick handler to each tag. Since the number in the id matches the number of sides, all we have to do is look for the number in the id. That's what this complicated thing does: this.id.match(/[0-9]+$/). It returns the string of numbers from the end of the id. And the great thing is, you don't have to know how it works. It just does.Obviously, you'll want to do something more interesting than alert the number of sides. You can add that part to the function too (eru's way of rolling the die was good), or you can simply save the value of sides. I made it a local variable, but you could easily make it a global variable. Then, if the user clicks something later, the script will remember what kind of die was selected.I left out the math and the spans and stuff so you could see more easily how to choose the number of sides. I hope you find it useful.
Link to comment
Share on other sites

So would my page look something like this?

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"   "http://www.w3.org/TR/html4/strict.dtd"><html>	<head>		<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">		<title></title>		<script type="text/javascript">			function init () { //is this a preset function or did you name it yourself as init?				var links = document.getElementsByTagName("a");				for (var i = 0; links[i]; i++) { /*May I ask what the "i" does. How come none of my links have a number yet this seems to give them a number?*/					links[i].onclick = function rolld() {						var sides = this.id.match(/[0-9]+$/); /* so this says match the id and find the first number and then give everything after that? Where can i learn this i haven't seen it on w3schools */						var d=(Math.floor(Math.random()*Number(sides)) + 1);						document.getElementById("d"+ sides +"result").innerHTML = d;						return false;					}				}			}			window.onload = init;		</script>	</head>	<body>		<div>			<a href="#" id="d20">Roll a d20</a> <span id="d20result"></span><br>			<a href="#" id="d12">Roll a d12</a><span id="d12result"></span></span><br>			<a href="#" id="d10">Roll a d10</a><span id="d10result"></span><br>			<a href="#" id="d100">Roll a d100</a><span id="d100result"></span><br>			<a href="#" id="d8">Roll a d8</a><span id="d8result"></span><br>			<a href="#" id="d6">Roll a d6</a><span id="d6result"></span><br>			<a href="#" id="d4">Roll a d4</a><span id="d4result"></span><br>			<a href="#" id="d3">Roll a d3</a><span id="d3result"></span><br>			<a href="#" id="d2">Roll a d2</a><span id="d2result"></span>		</div>	</body></html>

This works for me now. var links = tags<a> i get that, but then the for loop gives them a number, but I don't see what that has to do with anything? I am really confused I don't fully understand this code yet. (most of it being everything inside the head script.) I am having trouble understanding it even though I read and read over w3schools javascript tutorial every day and it's all so confusing. My current page with the one function is working fine, however I do wish to eventually expand it to do more things with dice, so it is important that I learn the premises behind these codes so I don't need to crutch off you guys forever :) . Again thanks for your help and any time you put into this. You are all very nice people!Eru

Link to comment
Share on other sites

EDIT. I wrote this before you made your changes. Maybe this will explain what's happening.---Well, the trouble is in this part: this.id.match(/[0-9]+$/). The working part is this /[0-9]+$/ . We call this a regular expression. It's used for matching and replacing text. If I'd written this, /dog/, the function would try to match the word "dog." Instead, I told it to match a range of characters, 0-9. NOT numbers, like 0-100. Just the digit characters. Putting them inside [ ] tells the function to look for any of the characters, not a complete string, like "dog". The "+" tells the function to look for multiple digits. The "$" tells it to find them at the end of the string.---About the "i". Have you never used a for loop? What I'm saying there is to loop around until a condition is met. i starts off as 0. Every time the loop starts over, the value of i goes up by one. That's what i++ does.Now, before I started the loop, I created an array that holds all the <a> elements. I called it links. So links[0] is the first <a>, links[1] is the second, and so on. Note: These numbers have NOTHING to do with the id numbers. This array works independently.When I put i inside the , and i increments in value, I am looping through ALL the <a> elements in the array. Looping is also called "iterating," and this is why programmers like to use "i" for this variable. The loop continues as long as links refers to a real object. When the value of i is higher than the number of <a> elements in the array, links returns as FALSE, and the loop stops running.I could have set up the loop like this, and it would do the same thing:for (var i = 0; i < links.length; i++)This way is probably more readable for a beginner. :)

Link to comment
Share on other sites

Yes ok, I understand this now. You never used the word "array" in the script so I was confused as to how it was working, but I suppose I will get better with time. I think that solves all my problems for now. I am going to experiment with some input fields for the user to input their own values into an equation: adx+b where a is the number of x-sided dice and b is a constant to add to the final value. I originally thought I could just generate a random integer between a and a*x however this assumes that all possibilities have an equal chance of coming up when in truth the probabilities are different. I now have to find a way to make the function roll a dice, store that variable and roll a new dice with the same number of sides and store it as a new variable, then take all the variables and add them together then add b. This would simulate the same odds of getting a number between a and a*x as if I truly rolled dice. But for now I think all my problems are solved. I will revert to huddling over my desk enjoying playing around with the javascript.I will make sure to add all of the names of the people who helped me to my page so that you guys get some of the credit!. Thanks everyone :) Eru

Link to comment
Share on other sites

In friendly, modern languages, when a function returns an array, you can assign it to a new variable without first calling new Array() or its equivalent.But now it's time I explained that getElementsByTagName() does not exactly return an array. It returns a "collection." That is, a DOM object rather than a true javascript object. So you can do some things with it, like access elements by index, and access its length property. But you can't use array functions like pop. It's a minor inconvenience.

Link to comment
Share on other sites

Hey guys I'm back. I feel really stupid but I've been playing around with this script and no matter how I do it, I can't add an If statement or the rest of the script doesn't function. It seems I can't add anything that isn't javascript. Heres the code:

function init () { var links = document.getElementsByTagName("a"); for (var i = 0; links[i]; i++) {   links[i].onclick = function rolld() {   var sides = this.id.match(/[0-9]+$/);    var d=(Math.floor(Math.random()*Number(sides)) + 1);   document.getElementById("d"+ sides +"result").innerHTML = d;   return false;  } }}window.onload = init;/* I want to add an if statement like this:If (d/sides <= .25 && > 0) { document.getElementById("d"+ sides +"result").style = color:red;}however, whenever I do that none of this script functions. */

Link to comment
Share on other sites

Hey guys I'm back. I feel really stupid but I've been playing around with this script and no matter how I do it, I can't add an If statement or the rest of the script doesn't function. It seems I can't add anything that isn't javascript. Heres the code:
function init () { var links = document.getElementsByTagName("a"); for (var i = 0; links[i]; i++) {   links[i].onclick = function rolld() {   var sides = this.id.match(/[0-9]+$/);    var d=(Math.floor(Math.random()*Number(sides)) + 1);   document.getElementById("d"+ sides +"result").innerHTML = d;   return false;  } }}window.onload = init;/* I want to add an if statement like this:If (d/sides <= .25 && > 0) { document.getElementById("d"+ sides +"result").style = color:red;}however, whenever I do that none of this script functions. */

First of all, this is a string: color:red. You have to put it between quotes.Second problem is this:d/sides <= .25 && > 0The computer has no idea what you're trying to compare to zero, you have to put it like this:
d/sides <= .25 && [b]d/sides[/b] > 0

Take these two things I told you, apply them to your code and see if it works.

Link to comment
Share on other sites

Thank-you Ingolme. I did apply those two things, but the script did not work so long as I had the If statement. I can't even put the word If after it in the code. I don't know what is stopping the other script from working. maybe it has something to do with the window.onload? i don't really know.Thanks again Ingolme,Eru

Link to comment
Share on other sites

Well, I was supposing the if() condition was inside the function. d and sides have no value outside of the function.
I tried putting it inside the function like this:
function init () { var links = document.getElementsByTagName("a"); for (var i = 0; links[i]; i++) {   links[i].onclick = function rolld() {   var sides = this.id.match(/[0-9]+$/);    var d=(Math.floor(Math.random()*Number(sides)) + 1);   document.getElementById("d"+ sides +"result").innerHTML = d;   return false;  } } If (d/sides <= .25 && d/sides >0) { document.getElementById("d"+ sides +"result").style = "color: red"; }}window.onload = init;

but it still fails to do any scripts :)

Link to comment
Share on other sites

Still not working

function init () { var links = document.getElementsByTagName("a"); for (var i = 0; links[i]; i++) {   links[i].onclick = function rolld() {   var sides = this.id.match(/[0-9]+$/);    var d=(Math.floor(Math.random()*Number(sides)) + 1);   document.getElementById("d"+ sides +"result").innerHTML = d;   return false;   If (d/sides <= .25 && d/sides >0) {	document.getElementById("d"+ sides +"result").style = "color: red";   }  } }}window.onload = init;

Link to comment
Share on other sites

Once the function reaches the "return false" line it returns back to the part of the application that called it. Therefore, anything written after a return line will not be executed.

Link to comment
Share on other sites

I don't mean to be denying you in every move but again I did what you say and the script still isn't running :) . The only other information I can give you that might help is that I am using notepad and firefox?

function init () { var links = document.getElementsByTagName("a"); for (var i = 0; links[i]; i++) {   links[i].onclick = function rolld() {   var sides = this.id.match(/[0-9]+$/);    var d=(Math.floor(Math.random()*Number(sides)) + 1);   document.getElementById("d"+ sides +"result").innerHTML = d;   If (d/sides <= .25 && d/sides >0) {	document.getElementById("d"+ sides +"result").style = "color: red";   }   return false;  } }}window.onload = init;

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...