简体   繁体   中英

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>

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/

Change:

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

To:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM