2014-06-22 11 views
5

ho questa parte del codicejquery: impostare min ingresso max nel tipo di opzione numero

<input type="number" min="2" max="10" step="2" id="contact" oninput="new_sum"> 

Nel campo posso inserire un numero> 10 e < 2.

Come posso limitarlo?

+3

È già limitato. Cosa intendi esattamente con "Come posso limitarlo?" – soktinpk

+2

Credo che stiano chiedendo se si digita un numero nel campo di input. Il limite non è gestito. – caspian

risposta

15

aggiungere una funzione onchange e impostare il valore se è fuori dall'intervallo.

$(function() { 
 
     $("#numberBox").change(function() { 
 
      var max = parseInt($(this).attr('max')); 
 
      var min = parseInt($(this).attr('min')); 
 
      if ($(this).val() > max) 
 
      { 
 
       $(this).val(max); 
 
      } 
 
      else if ($(this).val() < min) 
 
      { 
 
       $(this).val(min); 
 
      }  
 
     }); 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input id="numberBox" type="number" min="2" max="10" step="2" id="contact" />

+0

non funziona con il minimo. – user2519913

+0

hai ragione, ho avuto un errore di battitura - '($ this)' invece di '$ (this)'. Ho aggiornato la risposta e il violino. Dategli un'occhiata – caspian

+0

sì è corretto ora.È possibile bloccare il testo di input? dovrebbe funzionare solo con i pulsanti – user2519913

0

Si può avere una funzione generica per fare questo su tutti gli elementi in ingresso a gradino -

$(function() { 

    var limitInput = function() { 
     var value = parseInt(this.value, 10); 
     var max = parseInt(this.max, 10); 
     var min = parseInt(this.min, 10); 

     if (value > max) { 
      this.value = max; 
     } else if (value < min) { 
      this.value = min 
     } 
    }; 

    $("#numberBox").change(limitInput); 
}); 

FIDDLE

+1

non funziona. Esempio: inserisco 4 cambia in 10 (max) – user2519913

+0

@ user2519913 - Scusa - Aggiornamento della mia risposta e del violino. –

4

L'approccio che ho usato qui (anche se Ho creato un plugin per farlo) per verificare se il valore inserito è compreso nell'intervallo definito dallo min e Attributi max, se è è manteniamo tale valore; se non testiamo se il valore immesso è inferiore al valore min, se è allora abbiamo impostato il valore a valore min e in caso negativo (il che implica che il valore deve essere maggiore della max) abbiamo impostato il valore all'attributo max:

(function ($) { 
    $.fn.restrict = function() { 
     // returns the collection returned by the selector, over which we iterate: 
     return this.each(function(){ 
      // binding a change event-handler: 
      $(this).on('change', function(){ 
       // caching the 'this' (the current 'input'): 
       var _self = this, 
        // creating numbers from the entered-value, 
        // the min and the max: 
        v = parseFloat(_self.value), 
        min = parseFloat(_self.min), 
        max = parseFloat(_self.max); 
       // if it's in the range we leave the value alone (or set 
       // it back to the entered value): 
       if (v >= min && v <= max){ 
        _self.value = v; 
       } 
       else { 
        // otherwise we test to see if it's less than the min, 
        // if it is we reset the value to the min, otherwise we reset 
        // to the max: 
        _self.value = v < min ? min : max; 
       } 
      }); 
     }); 
    }; 
})(jQuery); 

$('#contact').restrict(); 

JS Fiddle demo.

Questo è un po 'ingenuo, in quanto il plug-in restrict() non verifica se il tipo di elemento <input> è number (ancora).

Redatta aggiungere un certo controllo di integrità per verificare che l'elemento è, infatti, di type="number":

(function ($) { 
    $.fn.restrict = function() { 
     return this.each(function(){ 
      if (this.type && 'number' === this.type.toLowerCase()) { 
       $(this).on('change', function(){ 
        var _self = this, 
         v = parseFloat(_self.value), 
         min = parseFloat(_self.min), 
         max = parseFloat(_self.max); 
        if (v >= min && v <= max){ 
         _self.value = v; 
        } 
        else { 
         _self.value = v < min ? min : max; 
        } 
       }); 
      } 
     }); 
    }; 
})(jQuery); 

JS Fiddle demo.

+0

grazie! È possibile bloccare il testo di input? dovrebbe funzionare solo con i pulsanti – user2519913

+1

Non che io ne sia a conoscenza, immagina quanto sarebbe difficile, ad esempio, uno smartphone o un tablet. –

0

Si può scrivere solo con jQuery:

$('#contact').prop('minLength', 2); 
$('#contact').prop('maxLength', 10); 
1

jquery ingresso impostato min max (tutti i tipi)

attributo

set min & attributo max in ingresso tag

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script> 
<input type="tel" class="form-control text-right ltr" data-min_max data-min="0" data-max="100" data-toggle="just_number" /> 

è possibile modificare min & max

dati-min = "0" data-max = "100"

Jquery

$(document).on('keyup', '[data-min_max]', function(e){ 
    var min = parseInt($(this).data('min')); 
    var max = parseInt($(this).data('max')); 
    var val = parseInt($(this).val()); 
    if(val > max) 
    { 
     $(this).val(max); 
     return false; 
    } 
    else if(val < min) 
    { 
     $(this).val(min); 
     return false; 
    } 
}); 

$(document).on('keydown', '[data-toggle=just_number]', function (e) { 
    // Allow: backspace, delete, tab, escape, enter and . 
    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 || 
     // Allow: Ctrl+A 
     (e.keyCode == 65 && e.ctrlKey === true) || 
     // Allow: Ctrl+C 
     (e.keyCode == 67 && e.ctrlKey === true) || 
     // Allow: Ctrl+X 
     (e.keyCode == 88 && e.ctrlKey === true) || 
     // Allow: home, end, left, right 
     (e.keyCode >= 35 && e.keyCode <= 39)) { 
      // let it happen, don't do anything 
      return; 
    } 
    // Ensure that it is a number and stop the keypress 
    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) { 
     e.preventDefault(); 
    } 
}); 

ESEMPIO: jsfiddle

1

Un modo più semplice e dinamico per non consentendo il da utente a digita o incolla valori fuori dall'intervallo né alcun altro carattere non numerico (senza la necessità di eseguire manualmente l'analisi o la rilevazione di chiavi):

$('input[type=number]').on('mouseup keyup', function() { 
 
    $(this).val(Math.min(10, Math.max(2, $(this).val()))); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="number" step="2" id="contact">

Se l'evento specifico è necessario solo per utilizzare un particolare ingresso del id, cioè $('#contact').on(...). Spiegazione: questi Math functions confrontare con Infinity in assenza di un argomento.

Nota: mouseup può anche essere utilizzato per impedire all'utente di incollare o utilizzare le frecce con il cursore.

Problemi correlati