2015-10-06 11 views

risposta

12

Purtroppo non è possibile, in pura HTML5, per raggiungere questo obiettivo. Javascript sarà richiesto ...

<input id="hourInput" type="number" min="1" max="24" step="1" onchange="if(parseInt(this.value,10)<10)this.value='0'+this.value;" /> 

EDIT: Dal momento che questa risposta sembra per ottenere un buon traffico, vorrei aggiungere il fatto che l'approccio che ho proposto è un modo ingenuo di farlo e solo la volontà funziona correttamente con un attributo min superiore a -9. Se il numero scende, lo 0 verrà comunque aggiunto con 0-234 quando l'utente immette un valore negativo di 234.

+1

Funzionerà anche: Dudi

+0

Ho creato una direttiva js angolare utilizzando questo concetto, https://github.com/ksnimmy/txDataType – Nimmy

+0

Penso che, se si utilizza l'evento di input, il comportamento sarà migliore. –

5

Non esiste un modo nativo per farlo. Tuttavia è possibile utilizzare l'evento oninput per formattare.

<input id="hourInput" type="number" oninput='format(this)' min="1" max="24" step="1" /> 

Javascript

function format(input){ 
    if(input.value.length === 1){ 
    input.value = "0" + input.value; 
    } 
} 

http://jsbin.com/dedixapasi/edit?html,js,output

+0

Great !, Tuttavia, in modo più semplice: Dudi

0

È anche possibile fare utilizzando jQuery come segue:

$(document).ready(function() { 
 
\t $("#hourInput").keydown(function(event) { 
 
\t \t if (event.keyCode == 46 || event.keyCode == 8) { 
 
\t \t \t 
 
\t \t } 
 
\t \t else { 
 
\t \t \t if (event.keyCode < 48 || event.keyCode > 57) { 
 
\t \t \t \t event.preventDefault(); \t 
 
\t \t \t } \t 
 
\t \t } 
 
\t }); 
 
    $("#hourInput").keyup(function(event) { 
 
     var str = $('#hourInput').val(); 
 
     if(str > 24) 
 
     { 
 
      $('#hourInput').val(str.substring(0,str.length - 1)); 
 
     } 
 
     
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 
<input id="hourInput" type="number" min="1" step="1" />

Spero che aiuti.

Problemi correlati