Reputation: 1330
i want to print the value of a javascript function on screen. how do i do that? sorry, im new to javascript. This is what i have done so far...
< button onclick="eng += 1; myFunction(eng,'Engaged: ');">Engaged< /button> // i wanna print the value of engaged here.
var eng = 0;
function myFunction( i,txt ){
var plural;
if ( i != 1 ) plural = "s.";
else plural = ".";
alert(txt + i + " time" + plural);
}
the value of engaged is incremented each time i click on it and is shown in the alert box. but i want to show it near to the buton. is there a way to do it?? thanks.
Upvotes: 0
Views: 3838
Reputation: 103155
You can create an element near the button say:
<div id="display"></div>
and your function can write to this like this:
document.getElementById("display").innerHTML = txt + i + " time" + plural;
So based on the comment below You can pass another parameter to your function. The ID of the element to update.
function myFunction( i,txt, elemid ){
var plural;
if ( i != 1 ) plural = "s.";
else plural = ".";
document.getElementById(elemid).innerHTML = txt + i + " time" + plural;
}
Then each button can call the function with the name of the element to update.
e.g.
<button onclick="eng += 1; myFunction(eng,'Engaged: ', 'display_engaged');">Engaged</button> <div id="display_engaged"></div>
And each button will have a corresponding element.
Upvotes: 1
Reputation: 6740
Sure you can do that easily.
After your button declaration, add a span tag with a unique id, such as:
<button ..>
<span id="engaged_value"></span>
And replace your alert with:
document.findElementById('engaged_value').innerHtml = txt + i + " time" + plural;
Upvotes: 0
Reputation: 24088
Put something like a <span id="spanID"></span>
next to your button
and then use the following javascript
document.getElementById('spanID').innerHTML = txt + i + " time" + plural";
Upvotes: 2