How to format the mm/yy field in Javascript?

Asked

Viewed 52 times

1

Watch the HTML code;

   <div class="form-group">
                      <label for="inputEmail3" class="col-sm-2 control-label">Período:</label>
                      <div class="row">
                          <div class="col-sm-2">
                            <input autocomplete="off" id="idPeriodoInicio" class="form-control monthPicker listar_uj" name="periodoInicio" id="periodoInicio"  placeholder="Período Inicial">
                          </div>
                           <div class="col-sm-2">
                            <input autocomplete="off"  id="idPeriodoFim" class="form-control monthPicker listar_uj" name="periodoFim" id="periodoFim" placeholder="Período Final">
                          </div>

                      </div>
                    </div>

Is it possible to use this line code only to format the field? I don’t want to appear any calendar, I just want to simply at the time the user enters the field it validate the field with formatting.

function carregaCalendario(){   
            $(".monthPicker").datepicker({
                dateFormat: 'MM/yy',
                changeMonth: true,
                changeYear: true,
                showButtonPanel: false,
                monthNamesShort: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'],
               // monthNames: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'],

                onClose: function(dateText, inst) {
                    var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
                    var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
                    $(this).val($.datepicker.formatDate('mm/yy', new Date(year, month, 1)));
                }
            });

            $(".monthPicker").focus(function () {
                $(".ui-datepicker-calendar").hide();
                $("#ui-datepicker-div").position({
                    my: "center top",
                    at: "center bottom",
                    of: $(this)
                });
            });
        }

2 answers

3

You can use jQuery with Maskedinput.

The libraries are these

<script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery.maskedinput/1.4.1/jquery.maskedinput.min.js"></script>

From what I understand you want a mask only with the month and the year.

It would look like this in mm/yy format

Html

<div class="form-group">
                      <label for="inputEmail3" class="col-sm-2 control-label">Período:</label>
                      <div class="row">
                          <div class="col-sm-2">
                            <input autocomplete="off" id="idPeriodoInicio" class="form-control monthPicker listar_uj" name="periodoInicio" id="periodoInicio"  placeholder="Período Inicial">
                          </div>
                           <div class="col-sm-2">
                            <input autocomplete="off"  id="idPeriodoFim" class="form-control monthPicker listar_uj" name="periodoFim" id="periodoFim" placeholder="Período Final">
                          </div>

                      </div>
                    </div>

jQuery

$(document).ready(function () {
        $('#idPeriodoInicio').mask('99/99');
        $('#idPeriodoFim').mask('99/99');
    });

You can see it working here > http://jsfiddle.net/m9ngvpk6/

1


With pure Javascript you can format the field by adding a bar when the number of characters is equal to 2.

Just you pick up the fields by the common class .monthPicker and apply a onkeydown in each input. When typing in the field, a bar will be added when it has 2 characters.

Can also put maxlength="5" to limit the number of characters in the input.

In the example below I put still to accept only numbers in the fields:

document.addEventListener("DOMContentLoaded", function(){
   
   // seleciona todos os campos pela classe
   var datas = document.querySelectorAll(".monthPicker");
   // teclas de controle (backspace, tab, ctrl etc.)
   var p = [8,9,13,16,17,35,36,37,39,46];
   
   for(var x=0; x<datas.length; x++){
      
      datas[x].onkeydown = function(e){
         
         var kcode = e.which || e.keyCode; // código da tecla
         var key = e.key; // valor da tecla
         
         // evita teclas que não sejam números
         // e as teclas que não sejam de controle
         // ao mesmo tempo
         if( /\D/.test(key) && !~p.indexOf(kcode) ){
            e.preventDefault(); // anula o efeito do evento keydown
            return; // sai da função
         }
         
         // se o número de caracteres for igual a 2
         // concatena a barra
         if(this.value.length == 2 && kcode != 8) this.value += "/";
         
      }
      
   }
   
});
<div class="form-group">
 <label for="inputEmail3" class="col-sm-2 control-label">Período:</label>
 <div class="row">
     <div class="col-sm-2">
       <input type="text" maxlength="5" autocomplete="off" id="idPeriodoInicio" class="form-control monthPicker listar_uj" name="periodoInicio" placeholder="Período Inicial">
     </div>
      <div class="col-sm-2">
       <input type="text" maxlength="5" autocomplete="off"  id="idPeriodoFim" class="form-control monthPicker listar_uj" name="periodoFim" placeholder="Período Final">
     </div>

 </div>
</div>

Browser other questions tagged

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