How do I allow only digits in an input field?

Asked

Viewed 134 times

0

I implemented the routine to check whether pressing a key in the INPUT field only type digits. In the first field it works normally, but when adding the second field it no longer works. Does anyone know what the problem is?

$(document).ready(function () {
  var bloco = $('[class^="bloco_"]');
  var current_id = parseInt(bloco.attr("class").split("_")[1], 10);
  
  $('input').bind('keypress', function (e) {
    // if the letter is not digit then display error and don't type anything
    if (e.which !== 8 && e.which !== 0 && (e.which < 48 || e.which > 57)) {
      //display error message
      $('.errmsg').css('color', 'red');
      $('.errmsg').html('Digits Only').show().fadeOut('slow');
      return false;
    }
  }).unbind('keypress').bind('keypress', function (e) {
    // if the letter is not digit then display error and don't type anything
    if (e.which !== 8 && e.which !== 0 && (e.which < 48 || e.which > 57)) {
      //display error message
      $('.errmsg').css('color', 'red');
      $('.errmsg').html('Digits Only').show().fadeOut('slow');
      return false;
    }            
  });

  $(document).on('click', '.btn-add', function (e) {
    e.preventDefault();
    var div_elements  = $('form:first .elements');            // SELECIONA DIV ELEMENTS   
    var div_bloco     = div_elements.find('.bloco_01:first'); // SELECIONA 1o BLOCO
    var last_class_number = parseInt(div_elements.find('div[class^=bloco_]:last').attr("class").split("_")[1], 10); // PEGA NUM DO ULTIMO BLOCO           
    
    nextElement(div_bloco, last_class_number);     
    div_elements.find('div[class^=bloco_]:last span')
    .removeClass('glyphicon-plus')
    .addClass('glyphicon-minus')
    .parent('button.btn-add')
    .removeClass('btn-add')
    .addClass('btn-del');    
    
    $('div[class^=bloco_]:last input').val('');

    $(this).unbind('click').on('click', '.btn-add', function(e) {
      div_elements.find('div[class^=bloco_]:last span')
      .removeClass('glyphicon-plus')
      .addClass('glyphicon-minus')
      .parent('button.btn-add')
      .removeClass('btn-add')
      .addClass('btn-del');                    

      $('div[class^=bloco_]:last input').val('');
    });
  
  }).on('click', '.btn-del', function (e) {
    e.preventDefault();            
    var bloco = $(this).parent().parent().parent().parent().attr('class');                        
    $('.' + bloco).remove();

    $(this).unbind('click').on('click', '.btn-del', function(e) {
      $('.' + bloco).remove();
    });
  });        

  function nextElement(element, current_id) {
    var newElement = element.clone();
    var id = current_id + 1;

    current_id = id;

    if (id < 10)
      id = "0" + id;

    var div_class_bloco = element.attr("class");

    newElement.attr("class", div_class_bloco.split("_")[0] + "_" + id);
    newElement.appendTo($(".elements"));
  }  

}); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
  <div class="col-sm-12">
    <form id="certameForm" class="form-horizontal" method="POST" action="teste_etapa11.php">
      <div class="elements">
        <div class="bloco_01">
          <!-- Secretaria -->
          <div class="form-group">
            <div class="col-sm-11 inputGroupContainer">
              <label class="col-sm-2 control-label">Secretaria</label>
              <div class="col-sm-9">
                <select class="form-control" id="cd_secretaria[]" name="cd_secretaria[]">
                  <option value="0">--Selecione a Secretaria--</option>
                  <option value="1">Administracao</option>
                  <option value="2">Assuntos Juridicos</option>
                  <option value="3">Chefia de Gabinete do Prefeito</option>
                  <option value="4">Cidadania, Assistencia e Inclusao Social</option>
                  <option value="5">Comunicacao</option>
                  <option value="6">Cooperacao Internacional</option>
                </select>
              </div>
              <div class="col-sm-1">
              </div>
            </div>
          </div>
          <div class="form-group">
            <div class="col-sm-11 inputGroupContainer">
              <label for="nu_qtd_vagas_por_secretaria[]" class="col-sm-2 control-label">Qtde Vagas por Secretaria</label>
              <div class="col-sm-9">
                <input type="text" class="form-control" id="nu_qtd_vagas_por_secretaria[]" name="nu_qtd_vagas_por_secretaria[]" placeholder="Quantidade de vagas por Secretaria" size="2" maxlength="2">
                <span class="errmsg"></span>
              </div>
            </div>
          </div>
          <!-- plus -->
          <div class="form-group">
            <div class="col-sm-11 inputGroupContainer">
              <div class="col-sm-offset-10 col-sm-1">
                <button class="btn btn-primary btn-md btn-add">
                  <span class="glyphicon glyphicon-plus"></span>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- Accept box and button submit -->
      <div class="form-group">
        <div class="col-sm-11 inputGroupContainer">
          <div class="col-sm-offset-3 col-sm-8">        
            <ul class="list-unstyled pull-right">
              <li><button type="submit" class="btn btn-primary next-step" id="submitted" name="submitted">Salvar e Continuar</button></li>
            </ul>
          </div>
        </div>
      </div>
    </form>
  </div>
</div>

Fiddle next: https://jsfiddle.net/rbastida/bk1kxztr/4/

  • in fiddle add field is not working!

3 answers

1

You can use type="number" or validate what is typed with javascript.

$("input.inteiro").keyup(function (e) { // Filtro o que não é digito
    if (/\D/g.test($(this).val())) $(this).val($(this).val().replace(/\D/g, ''));
});
$("input.numerico").keyup(function (e) { // Filtro o que não é numérico
    var tVal=$(this).val();
    if (tVal!="" && isNaN(tVal)){
        tVal=(tVal.substr(0,1).replace(/[^0-9\.\-]/, '')+tVal.substr(1).replace(/[^0-9\.]/, ''));
        var raVal=tVal.split(".")
        if(raVal.length>2)
            tVal=raVal[0]+"."+raVal.slice(1).join("");
        $(this).val(tVal);
    } 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <p>Campos numéricos utilizando somente html:</p>
  <input type="number" />
</div>
<div>
  <p>Somente inteiros utilizando expressão regular com replace:</p>
  <input type="text" class="inteiro" />
</div>
<div>
  <p>Somente numéricos utilizando expressão regular com replace:</p>
  <input type="text" class="numerico" />
</div>

0

Use the .delegate(). It will include new elements to the function.

Replace the line

$('input').bind('keypress', function (e) {

for

$(document).delegate('input','keypress', function (e) {

Although the method .delegate() is marked as "discontinued" us jQuery Docs, it still works in its latest version.

Updating:

Like the .delegate() and the .bind() has been discontinued, in place it is recommended to use .on(). In this case, the correct one is to select only the set of elements to which you want to apply the function. Instead of selecting the whole document $(document), select only the form in question:

$("#certameForm"). on('keypress', 'input', Function (and) {

0

Modify the following line:

$('input').bind('keypress', function (e) {

To:

$(document).on('keypress', 'input', function (e) {

Doing this, the function that checks whether it was typed only digits and displays the error message will work also for the new elements created dynamically on the page.

In addition to the modification mentioned above, I removed a part of the function that checks if it was typed only digits and displays the error message, because it was duplicated in the original code.

Before:

  $('input').bind('keypress', function (e) {
    // if the letter is not digit then display error and don't type anything
    if (e.which !== 8 && e.which !== 0 && (e.which < 48 || e.which > 57)) {
      //display error message
      $('.errmsg').css('color', 'red');
      $('.errmsg').html('Digits Only').show().fadeOut('slow');
      return false;
    }
  }).unbind('keypress').bind('keypress', function (e) {
    // if the letter is not digit then display error and don't type anything
    if (e.which !== 8 && e.which !== 0 && (e.which < 48 || e.which > 57)) {
      //display error message
      $('.errmsg').css('color', 'red');
      $('.errmsg').html('Digits Only').show().fadeOut('slow');
      return false;
    }            
  });

Afterward:

  $(document).on('keypress', 'input', function (e) {

        //   if the letter is not digit then display error and don't type anything
        if (e.which !== 8 && e.which !== 0 && (e.which < 48 || e.which > 57)) {
            //display error message
            $('.errmsg').css('color', 'red');
            $(this).closest('div').find('.errmsg').html('Digits Only').show().fadeOut('slow');
            return false;
        }

    });

Following demonstration of the functioning of your code after the changes:

$(document).ready(function () {

    var bloco = $('[class^="bloco_"]');
    var current_id = parseInt(bloco.attr("class").split("_")[1], 10);

    $(document).on('keypress', 'input', function (e) {
        //   if the letter is not digit then display error and don't type anything
        if (e.which !== 8 && e.which !== 0 && (e.which < 48 || e.which > 57)) {
            //display error message
            $('.errmsg').css('color', 'red');
            //Busca o elemento com class .errmsg que esteja na mesma div do input alterado e exibe a mensagem de alerta
            $(this).closest('div').find('.errmsg').html('Digits Only').show().fadeOut('slow');
            return false;
        }
    });

    $(document).on('click', '.btn-add', function (e) {

        e.preventDefault();

        var div_elements  = $('form:first .elements');            // SELECIONA DIV ELEMENTS   
        var div_bloco     = div_elements.find('.bloco_01:first'); // SELECIONA 1o BLOCO
        var last_class_number = parseInt(div_elements.find('div[class^=bloco_]:last').attr("class").split("_")[1], 10); // PEGA NUM DO ULTIMO BLOCO           

        nextElement(div_bloco, last_class_number);     

        div_elements.find('div[class^=bloco_]:last span')
            .removeClass('glyphicon-plus')
            .addClass('glyphicon-minus')
            .parent('button.btn-add')
            .removeClass('btn-add')
            .addClass('btn-del');    

        $('div[class^=bloco_]:last input').val('');

        $(this).unbind('click').on('click', '.btn-add', function(e) {

            div_elements.find('div[class^=bloco_]:last span')
                .removeClass('glyphicon-plus')
                .addClass('glyphicon-minus')
                .parent('button.btn-add')
                .removeClass('btn-add')
                .addClass('btn-del');                    

            $('div[class^=bloco_]:last input').val('');

        });        

    }).on('click', '.btn-del', function (e) {

        e.preventDefault();            
        var bloco = $(this).parent().parent().parent().parent().attr('class');                        
        $('.' + bloco).remove();

        $(this).unbind('click').on('click', '.btn-del', function(e) {

            $('.' + bloco).remove();

        });

    });        

    function nextElement(element, current_id) {

        var newElement = element.clone();
        var id = current_id + 1;

        current_id = id;

        if (id < 10)
            id = "0" + id;

        var div_class_bloco = element.attr("class");

        newElement.attr("class", div_class_bloco.split("_")[0] + "_" + id);
        newElement.appendTo($(".elements"));

    }  

});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">    
    <div class="col-sm-12">

        <form id="certameForm" class="form-horizontal" method="POST" action="teste_etapa11.php">
            <div class="elements">
                <div class="bloco_01">

                    <!-- Secretaria -->
                    <div class="form-group">
                        <div class="col-sm-11 inputGroupContainer">
                            <label class="col-sm-2 control-label">Secretaria</label>
                            <div class="col-sm-9">
                                <select class="form-control" id="cd_secretaria[]" name="cd_secretaria[]">
                                    <option value="0">--Selecione a Secretaria--</option>  
                                    <option value="1">Administracao</option>
                                    <option value="2">Assuntos Juridicos</option>
                                    <option value="3">Chefia de Gabinete do Prefeito</option>
                                    <option value="4">Cidadania, Assistencia e Inclusao Social</option>
                                    <option value="5">Comunicacao</option>
                                    <option value="6">Cooperacao Internacional</option>                                        
                                </select>
                            </div>
                            <div class="col-sm-1">
                            </div>
                        </div>
                    </div>  

                    <div class="form-group">
                        <div class="col-sm-11 inputGroupContainer">        
                            <label for="nu_qtd_vagas_por_secretaria[]" class="col-sm-2 control-label">Qtde Vagas por Secretaria</label>
                            <div class="col-sm-9">
                                <input type="text" class="form-control" id="nu_qtd_vagas_por_secretaria[]" name="nu_qtd_vagas_por_secretaria[]" placeholder="Quantidade de vagas por Secretaria" size="2" maxlength="2">
                                <span class="errmsg"></span>
                            </div>
                        </div>
                    </div>                                     

                    <!-- plus -->
                    <div class="form-group">
                        <div class="col-sm-11 inputGroupContainer">
                            <div class="col-sm-offset-10 col-sm-1">                 
                                <button class="btn btn-primary btn-md btn-add">
                                    <span class="glyphicon glyphicon-plus"></span>
                                </button>
                            </div>
                        </div>
                    </div>

                </div>
            </div>

            <!-- Accept box and button submit -->
            <div class="form-group">
                <div class="col-sm-11 inputGroupContainer">
                    <div class="col-sm-offset-3 col-sm-8">    
                        <ul class="list-unstyled pull-right">
                            <li><button type="submit" class="btn btn-primary next-step" id="submitted" name="submitted">Salvar e Continuar</button></li>
                        </ul>
                    </div>
                </div>
            </div>

  • Your code does not work properly because even when the field input not focused, pressing any key will call the function.

  • It’s still the same thing. Take the test.

  • Now it is no longer, what was generating the conflict was the duplicate code of the function that checks if it was typed only digits and displays the error message.

  • Would there be some way to only appear warning message for each individual input being typed, and not for everyone at the same time?

  • @Rogerbastida I edited the code with a way to display the alert message only for the input being changed.

  • It was good, only problem that I could not solve is the tracinho before the message "Digit Only" that appears after adding more than one field... Nor do I understand why sometimes it is necessary to use the unbind event before enabling the click again...

Show 1 more comment

Browser other questions tagged

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