How to make an auto sum function in javascript

Asked

Viewed 119 times

-2

How can I do a function in javascript that changes the total_productions field every time a field changes its value in the form? I have the following code
Template

<form class="form" role="form" method="POST" >
 <table class="table table-condensed table-responsive">
    <thead>
      <tr>
        <th>Produção Científica nos últimos 3 anos</th><th>Quantidade</th>
      </tr>
    </thead>
    <tbody>
      <tr>
          <td>{{ form.pc_artigos_qualis_a1_cinco_autores.label }}
          <td>{{ form.pc_artigos_qualis_a1_cinco_autores }}</td>
      </tr>
      <tr>
        <td>{{ form.pc_artigos_qualis_a1_mais_cinco_autores_primeiro_ultimo.label }}</td>
        <td>{{ form.pc_artigos_qualis_a1_mais_cinco_autores_primeiro_ultimo }}</td>
      </tr>
      <tr>
        <td>{{ form.total_producoes.label }}</td>
        <td>{{ form.total_producoes }}</td>
      </tr>
</tbody>
  </table>
</form>

I’m still learning to code in python Django, so I’m open to criticism of the code!

  • I didn’t understand and only with this information is difficult to help? Updates what?

  • then, in the code I have the "form.pc_artigos_qualis_a1_cinco_authors" and the "form.pc_artigos_qualis_a1_mais_cinco_autores_primeiro_ultimo", these two fields are of the whole type, and what I want to do is update the form.total_producoes field when one of them changes its value

  • They are text inputs???

  • yes yes, they are text

  • You made some javascript?

  • no, I was just researching and testing on my code but I wasn’t getting

Show 1 more comment

1 answer

0


From the comments I understood that you want to add values and bring to another input I decided to explain with a minimal example:

function change() {
  let v1 = parseInt(document.getElementById("v1").value) || 0;
  let v2 = parseInt(document.getElementById("v2").value) || 0;
  document.getElementById("res").value = v1 + v2;
}
window.onload = (function() { change() });
<div> 
  <input type="text" value="10" name="v1" id="v1" onkeyup="change()" />
</div>
<div> 
  <input type="text" value="10" name="v2" id="v2" onkeyup="change()" />
</div>
<div> 
  <input type="text" name="res" id="res" value="" />
</div>

  • 1

    exactly that! helped me to understand how it happens the use of javascript in a very simple way, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.