Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML incrementing voting system

I'm pretty new to html, I am trying to show a value on my web page that increments when a button is pressed.

Here is my code:

<script type ="text/javascript">
     var likesSD = 0;
     var dislikesSD= 0;
</script>
    <button class="like" onclick="likes++">I like!</button>
<script>document.write(likesSD);</script>

The value on the screen does not change when the button is pushed. Is there a way I can do that without using a database?

like image 417
user3091077 Avatar asked Mar 16 '26 17:03

user3091077


2 Answers

You can do this:

<div id="likes"></div>

<script type ="text/javascript">
    var likes = 0;

    function IncreaseLikes()
    {
        likes++;
        document.getElementById("likes").innerHTML = likes;
    }
</script>

<input type="button" class="like" onclick="IncreaseLikes()" value="I like!" />
  • Use some element to hold the value, It's not nice to use document.write();
  • I have changed your button to input type="button";
  • Whithout database the information will be lost on page refresh. You can use localStorage(supported in all modern browsers) in order to keep the value saved, but only in the browser. Still not valid for a real votting pool.
like image 54
DontVoteMeDown Avatar answered Mar 18 '26 06:03

DontVoteMeDown


You have to define a function that increments your like / dislike counter and then writes it to the document. Then map that function to the onclick event of your button:

<script type ="text/javascript">
     var likesSD = 0;
     var dislikesSD= 0;

     function like() {
         likesSD++;
         document.getElementById("likes").innerHTML = likesSD;
     }
</script>
    <button class="like" onclick="like()">I like!</button>
    <div id="likes"></div>
like image 33
RononDex Avatar answered Mar 18 '26 06:03

RononDex