Campo de Hora no deja digitar algunas
Publicado por Eduardo (186 intervenciones) el 10/03/2020 18:00:55
Hola a todos hace un mes un gran Colaborador de este foro me envío este script el cual sirve para poner en un campo de texto la forma Hora HH:MM en ese formato a medida que se va escribiendo...
pero pasa algo que no me di cuenta hasta ahora.
es que al escribir Horas no me deja escribir las horas de las 16:00 a las 19:00
es decir me permite por ejemplo digitar 12:30 o 14:20 o 15:00 pero no me deja terminar las 16.. ni las 17.. 18.. o 19..
pero luego si me deja del 20 al 23.... o antes del 16...
que hay que modificarle o adicionarle para que deje escribir las horas sin problema Muchas Gracias!!
acá dejo el Script...
pero pasa algo que no me di cuenta hasta ahora.
es que al escribir Horas no me deja escribir las horas de las 16:00 a las 19:00
es decir me permite por ejemplo digitar 12:30 o 14:20 o 15:00 pero no me deja terminar las 16.. ni las 17.. 18.. o 19..
pero luego si me deja del 20 al 23.... o antes del 16...
que hay que modificarle o adicionarle para que deje escribir las horas sin problema Muchas Gracias!!
acá dejo el Script...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
Hora: <input type="text" class="hora" size="5" autofocus />
<script>
document.querySelector('.hora').addEventListener('keypress',validateHour);
document.querySelector('.hora').addEventListener('blur',formatHour);
function validateHour(e){
e.preventDefault();
if ( !isNaN(e.key) || e.key==':' ) {
var position = this.selectionStart;
var text = this.value;
var textStart = text.substr(0,position);
var textEnd = text.substr(this.selectionEnd);
if ( (textStart+textEnd).search(':')!=-1 && e.key==':' ) return;
var textNew = textStart + e.key + textEnd;
textNew = textNew.replace(':','');
if ( textNew.length>2 ){
textStart = textNew.substr(0,textNew.length-2);
textEnd = textNew.substr(-2);
textNew = textStart + ':' + textEnd;
position++;
} else if ( textNew>59 ) {
textStart = textNew.substr(0,1);
textEnd = textNew.substr(1);
textNew = textStart + ':' + textEnd;
position++;
}
var textPart=textNew.split(':');
if ( textPart.length == 2 && textPart[0]>23 || textPart[1]>59 ) return;
this.value = textNew;
this.selectionStart = position+1;
this.selectionEnd = position+1;
}
}
function formatHour(){
var text = this.value;
if ( text!="" ) {
textPart = text.split(':');
if ( textPart.length == 2 ) {
textPart[0]=textPart[0].padStart(2,'0');
textPart[1]=textPart[1].padStart(2,'0');
} else {
textPart.push(textPart[0].padStart(2,'0'));
textPart[0]='00';
}
this.value=textPart.join(':');
}
}
</script>
Valora esta pregunta


0