How do I only allow digits in an input field?

0

I have implemented the routine to verify if pressing a key in the INPUT field is typed only in digits. The first field works normally, but adding the second field 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><linkhref="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>

Follow fiddle: link

    
asked by anonymous 24.08.2017 / 16:52

3 answers

1

You can use type="number" or make a validation of 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>Camposnuméricosutilizandosomentehtml:</p><inputtype="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>
    
24.08.2017 / 17:15
0

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

Replace the line

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

by

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

Although the .delegate() method is marked as " discontinued " in   jQuery docs, it still works on your latest version.

Updating:

Since .delegate() and .bind() has been discontinued, it is recommended to use .on() instead. 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, just select the form in question:

  

$ ("# certameForm"). on ('keypress', 'input', function (e) {

    
24.08.2017 / 19:28
0

Modify the following line:

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

To:

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

By doing this, the function that checks if only digits were entered and displays the error message will also work for the new dynamically created elements on the page.

In addition to the modification mentioned above, I removed a part of the function that checks to see if digits were only entered 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;
    }            
  });

Then:

  $(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 is the demonstration of how your code works 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><divclass="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>
    
24.08.2017 / 17:19