Aidan
Aidan

Reputation: 480

How to display a counter output to text rather than an input

I have created a basic JavaScript counter which counts the amount of times a button has been pressed and then it displays it in an input box.

I want to change it so that it counts the amount of times it is pressed and displays it as just text.

eg 5,123

HTML:

     <div class="col-md-2 col-md-offset-3">
   <div class="outer"><img src="assets/img/f1.jpg" alt="..." class="img-rounded" style="width:250px;height:150px"></div>
   <div class="inner">
     <center><button class="btn btn-default" value = "Click" onclick = "count()">Vote</button></center>
     <input id = "counting" type = "text" class="votecount" />

   </div> 
 </div>

CSS:

  .outer {
     position:absolute;
    }

  .inner {
     position:relative;
     margin-top:50px;
   }

  .votecount {
     width:50px;
   }

JAVASCRIPT:

 <script type ="text/javascript">

  var x = 0;
 function count()
 {
 x += 1;
  document.getElementById( "counting" ).value = x;
  }
   </script>

Upvotes: 0

Views: 228

Answers (3)

Muhammad Tahir
Muhammad Tahir

Reputation: 2485

use something like that.. first get value of count.. if there is no vote.. add 1 in it.. if there is already vote.. increment into it

 function count()
 {
  var x = document.getElementById("counting").value;
     if(x==""){
         document.getElementById( "counting" ).value = 1;
     }else{
         document.getElementById( "counting" ).value = parseInt(x)+1;
     }   

  }

here is the link for Fiddle http://jsfiddle.net/szWth/

Upvotes: 1

user571545
user571545

Reputation:

make the input a span and change your DOM query to alter "innerHTML": function count() { x += 1; document.getElementById( "counting" ).innerHTML = x; }

Upvotes: 0

SW4
SW4

Reputation: 71230

Change:

<input id = "counting" type = "text" class="votecount" />

To:

<span id = "counting" class="votecount"></span>

Upvotes: 0

Related Questions