Only accept multiples of X in the input

1

I need my input to only accept multiples of an X value that will be set via the function parameter. How can I proceed?

    
asked by anonymous 16.03.2015 / 16:26

2 answers

2

You can do in event blur of input , which checks whenever you lose focus :

var X = 2;

$("#entrada").blur(function() {
  var numero = parseInt($(this).val());
  if (!isNaN(numero)) {
    if (numero % X === 0) {
      $("#saida").html("É múltiplo de " + X );
    } else {
      $("#saida").html("Não é múltiplo de " + X );
    }
  } else {
    $("#saida").html("Entrada não é um número.");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text" id="entrada">
<p id="saida"></p>
    
16.03.2015 / 17:49
3

You can use HTML5 validation with a input of type #

Using the number method you can specify a validation with a custom error message. To indicate that there is no error, just call setCustomValidity(mensagem) by passing an empty string as a parameter.

The pseudo-class setCustomValidity() is added to the HTML5 element that does not validation. In CSS you can use the :invalid selector to apply a specific style to elements with an error.

Example of operation:

$(function(){
  // deve ser múltiplo
  var mult = 4;
  
  $('#num').keyup(function(){
    var val = parseInt($(this).val());

    if(val % mult != 0) {
      // [0] aqui é usado para acessar diretamente o elemento DOM, já que o método setCustomValidity é não é do jQuery
      $(this)[0].setCustomValidity("Digite um múltiplo de " + mult + ".");
    } else {
      $(this)[0].setCustomValidity("");
    }
  });
});
input[type="number"]:invalid {
  background-color: #f2dede;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><form><inputtype="number" value="" id="num" /><br />
  <button>Enviar</button>
</form>
    
16.03.2015 / 17:54