Search code examples
javascriptimagebuttonbuttonclickdocument.write

Change value with onclick and javascript function


I am trying to change the value "qa". The js function works fine. However, I am not able to change the value "ID1" between span. When I click the image button plus, I want to change the value to 2 i.e. change value with one step, see also screenshot. The value 1 in the screenshot comes from document.write(qa). I am new to this and I would appreaciate any help, thanks!

Image: click on plus to change value with step 1 like from 1 to 2

   
var qa = 1;

function adq(x) {
  qa = qa + x;
} 
  
<html>
<div id="Group_1">
  <input type="image" id="Goup_m_1" src="some.png" name="submit_plus" onclick="adq(1)">
  <div id="Value">
    <span>Value</span>
  </div>
  <div id="ID1">
   <span>
     <script>
         document.write(qa);
     </script>
   </span>
</html>


Solution

  • To show the incremental value you have to get the div (document.getElementById("ID1")) and set innerHTML property in this way:

    function adq(x) {
      qa = qa + x;
      document.getElementById("ID1").innerHTML = qa;
    } 
    <html>
    <div id="Group_1">
      <input type="image" id="Goup_m_1" src="some.png" name="submit_plus" onclick="adq(1)">
      <div id="Value">
        <span>Value</span>
      </div>
      <div id="ID1">
       <span>
         <script>
             var qa = 1;
             document.write(qa);
         </script>
       </span>
       </div>
    </html>