PDA

View Full Version : Simple HTML question


dondrei
01-16-2006, 08:58 AM
Hi. I'm new to HTML/Javascript editing and I just wanted to make a simple html code that has a button, and underneath it says "You have pressed this button X times", and of course every time you press the button X goes up by one. I thought this would be trivial to do but I can't figure it out...

Viath
01-16-2006, 09:44 AM
Here's a quickie that will give you a basic idea:

<script type="text/javascript">
function inClick(theForm) {
theForm.clicked.value++
return false
}
</script>
<form name="clicker" onsubmit="return inClick(this)">
<input type="submit" value="Click Me" /><br />
You clicked me <input type="text" name="clicked" value="0" /> times.
</form>

dondrei
01-16-2006, 06:32 PM
That's great, thanks. Is there any way to make it display the number not in a box so that people can't manually enter a number into it?

_Aerospace_Eng_
01-16-2006, 06:34 PM
<input type="text" name="clicked" value="0" readonly="readonly" />

dondrei
01-17-2006, 05:05 AM
Ah, there's a "readonly" option. Thanks.

I'm also thinking of trying to get it to do something a little more complex - is it possible to have the counter permanently store the number of times it's been pressed? So I can put this webpage up on the net and have the total number of times it's been pressed by everyone up on the screen.

Viath
01-17-2006, 06:00 AM
You could set a cookie, however, the cookie will not be available to the page that initially sets the cookie, unless it's refreshed.

For JavaScript cookie functions, check here:
http://www.netspade.com/articles/2005/11/16/javascript-cookies/

If you can use PHP that is always a much better option.

One last suggestion, don't forget you can use CSS to make that input text field look like normal text:

<input type="text" name="clicked" value="0" readonly="readonly" style="border:0px;background-color:#FFFFFF;color:#000000;width:30px" />

dondrei
01-19-2006, 06:36 AM
Okay, I've been fiddling around with cookies for a bit, but I can't figure out how to tell it to add one to the cookie value every time the button is pressed. I need something like:

document.cookie=document.cookie+1

But I can't figure out what the right syntax is. Also, is there any way to store the number of times the button has been pressed by ALL people who access the site?

Viath
01-23-2006, 01:04 PM
The thing with cookies is that the browser reads the cookie when it loads the page, after that it doesn't care about the cookie at all, so even if the cookie's value is incremented the browser will not know about it until the page is re-loaded.

This also means that even if your script increments the cookie value a million times, the browser will keep adding it to the original value the cookie had when the page loaded.

In other words, unless the page is refreshed and the browser reads the new value, it won't work the way you want it to.