Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

241
Vistas
Javascript: How to calculate the total number of months?

I have wrote a code to split the input into two variables i.e. year and month. But, I am unable to make it work. It does not return the total number of months into the respective text field. Please help me debug my code.

$(function() {
  $("#duration").keyup(function() {
    var input = document.getElementById('duration').value;
    var fields = input.split('.');
    var years = fields[0];
    var months = fields[1];
    var result = years.val() * 12 + months.val();
    document.getElementById("totalNumMonths").innerHTML = result;
  });
});
<html>
<body>
  <table>
    <tr>
      <td>Calculate Months</td>
      <td>
        <label>Input Years in the format (year.month e.g. 11.6)</label>
        <input class="form-control" name="duration" id="duration" value="" type="number" />
        <br/>
        <label>Total Months</label>
        <input class="form-control" name="totalNumMonths" id="totalNumMonths" value="" type="number" />
      </td>
    </tr>
  </table>
</body>
</html>

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Issues with code that I identified and fixed.

  • You dont need to access years.val() and months.val() because years and months holds string value.
  • If your input doesnot have a dot, the value for months will be undefined, so you can define years and months as fields[0] || "0" and fields[1] || "0" respectiveley.
  • Since element with id totalNumMonths is an input. You should set the value and not innerHTML
  • Since the years and months value produces a string, I have added a + symbol infront of them while setting the value for #totalNumMonths to convert them to number, since we are performing numiric action. Else + symbol on string will perform string concatenation.

Working Fiddle

$(function () {
  $("#duration").keyup(function () {
    var input = document.getElementById('duration').value;
    var fields = input.split('.');
    var years = fields[0] || "0";
    var months = fields[1]  || "0";
    var result = +years * 12 + +months;
    document.getElementById("totalNumMonths").value = result;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<table>
  <tr>
    <td>Calculate Months</td>
    <td>
      <label>Input Years in the format (year.month e.g. 11.6)</label>
      <input class="form-control" name="duration" id="duration" value="" type="number" />
      <br />
      <label>Total Months</label>
      <input class="form-control" name="totalNumMonths" id="totalNumMonths" value="" type="number" />
    </td>
  </tr>
</table>

about 4 years ago · Juan Pablo Isaza Denunciar

0

You were calling val on string elements, which caused errors. And the result was adding months as a string value.

$(function () {


    $("#duration").keyup(function () {
    
  
        var input = document.getElementById('duration').value;

        var fields = input.split('.');

        
        var years = parseInt(fields[0]); 
        var months = parseInt(fields[1]);
        
        var result = (years * 12) + months;
        
        document.getElementById("totalNumMonths").value = result;


  });


});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
 <body>
  <table>
   <tr>
    <td>Calculate Months</td>
    <td>
    <label>Input Years in the format (year.month e.g. 11.6)</label>
    <input class="form-control" name="duration" id="duration" value="" type="number"/>
    <br/>
    <label>Total Months</label>
    <input class="form-control" name="totalNumMonths" id="totalNumMonths" value="" type="number"/>
    </td>
   </tr>


  </table>
 </body>
</html>

about 4 years ago · Juan Pablo Isaza Denunciar

0

In the code snippet, you are having the value of years & months in the respective variables, so you don't need to use years.val() to get that value.

Check this out!!

$(function() {
  $("#duration").keyup(function() {
    var input = document.getElementById('duration').value;
    var fields = input.split('.');
    var years = fields[0];
    var months = fields[1] || 0;
    var result = years * 12 + months;
    document.getElementById("totalNumMonths").innerHTML = result;
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>Calculate Months</td>
    <td>
      <label>Input Years in the format (year.month e.g. 11.6)</label>
      <input class="form-control" name="duration" id="duration" value="" type="number" />
      <br/>
      <label>Total Months :</label>
      <!-- <input class="form-control" name="totalNumMonths" id="totalNumMonths" value="" type="number" /> -->
      <span id="totalNumMonths">0</span>
    </td>
  </tr>
</table>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda