JavaScript - Me repite el mismo valor en campos siguientes.. Ayuda Por fa

 
Vista:
Imágen de perfil de Eduardo
Val: 159
Ha mantenido su posición en JavaScript (en relación al último mes)
Gráfica de JavaScript

Me repite el mismo valor en campos siguientes.. Ayuda Por fa

Publicado por Eduardo (176 intervenciones) el 11/11/2022 20:46:05
Hola a todos espero me puedan ayudar.. tengo este problema el cual me repite en el siguiente capo el mismo valor del primero y debería ser el resultado de la resta de horas del segundo.. y así sucesivamente.. acá les muestro de que hablo.... (trabajo con clases)


ejemplo

como ven me repite y eso que trabajo con clases..

acá publico el código completo para que me puedan ayudar a solucionarlo.. Mil graciass amigos!! se que es mucho pedir pero ya no doy y no quiero dañar lo que llevo hasta ahora.. Ayudaa por favor!!

Es en la parte de Javascript

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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
<?php include("segu.php");?>
<?php
    header('Content-Type: text/html; charset=ISO-8859-1');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//ES" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta charset="utf-8" />
<title>Formulario Detalle Conductores</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/select2.css">
<script src="js/select2.js"></script>
<script>
jQuery(document).ready(function($){
    $(document).ready(function() {
        $('.selector').select2();
    });
});
</script>
<?php
$time2 = time();
$rand=rand(5, 15);
$codigo= $rand.$time2;
$municcc=$_SESSION['municipio'];
?>
<?php
$fechaActual = date('Y-m-d H:i:s');
  $mysqli = new mysqli('localhost', 'usuario', 'clave', 'basededatos');
  ?>
       <?php
 
 	$connection = mysql_connect("localhost", "usuario", "clave");
	mysql_select_db("basededatos", $connection);
	 $result = mysql_query("SELECT * FROM operarios_nom WHERE estado='activo'", $connection);
	$array = array();
	if($result){
		while ($row = mysql_fetch_array($result)) {
			$equipo = utf8_encode(strtoupper ($row['nombre']));
			array_push($array, $equipo);
		}
	}
?>
<!-------------------------EXTRAS------------------------------------->
<script>
var fieldHTML3 = '<div id="destino2">   <label> Operario Extra: </label><select name="operariohoraextra[]" required="required" class="campos selector" id="operariohoraextra"><option value="">Seleccione:</option><?php $query = $mysqli -> query ("SELECT * FROM operarios_nom WHERE estado='activo' AND municipio='$municcc' ORDER BY nombre ASC"); while ($valores = mysqli_fetch_array($query)){echo '<option value="'.strtoupper($valores[nombre]).'">'.strtoupper($valores[nombre]).'</option>';}?></select><label> Como: </label><select name="tipohoraextra[]" id="tipohoraextra" required="required" class="campos selector"><option value="">Seleccione</option><option value="Recolector">Recolector</option><option value="Escobita">Escobita</option><option value="Alimentador">Alimentador</option><option value="Apoyo">Apoyo</option><option value="Otro">Otro</option></select><label> Inicia: </label><input type="text" name="horaextra[]" value="" autocomplete="off" required="required" maxlength="5" class="hora5" id="horaextra" size="2"/><label> Finaliza: </label><input type="text" name="horaextra2[]" value="" autocomplete="off" required="required" maxlength="5" class="hora6" id="horaextra2" size="2"/>- <input name="horaextra[]" type="text" required="required" class="horaextrat" autocomplete="off" size="2" maxlength="5" readonly="readonly"/><label> Nota: </label> <input name="observacionesextra[]" type="text" id="observacionesextra" size="14" /> <label>Placa: </label><input name="placa_extra[]" type="text" id="placa_extra" size="5" style="text-transform:uppercase;" onkeyup="javascript:this.value=this.value.toUpperCase();" autocomplete="off"/> <a href="javascript:void(0);" class="remove_button" title="Borrar Hora Extra"><img src="remove-icon.png" width="20" height="20"/></a></div>'; //New input field html
 </script>
  <script>
    $(document).ready(function(){
    var maxField3 = 30; //
    var addButton3 = $('.add_button3'); //agrega
    var wrapper3 = $('.field_wrapper3'); //wrapper
	var x = 1; //Initial field counter is 1
    $(addButton3).click(function(){ //Once add button is clicked
        if(x < maxField3){ //Check maximum number of input fields
            x++; //Increment field counter
            $(wrapper3).append(fieldHTML3); // Add field html
			$('.selector').select2();
        }
    });
    $(wrapper3).on('click', '.remove_button', function(e){ //Once remove button is clicked
        e.preventDefault();
        $(this).parent('div').remove(); //Remove field html
        x--; //Decrement field counter
    });
	//JUEGO DE CAMPOS-------------------------------------------------
		$(wrapper3).on('keypress','.hora5',validateHour); //para el elemento dentro de destino que tenga la clase "hora", cuando se presione la tecla ejecuta la función validateHour
		$(wrapper3).on('blur','.hora5',formatHour);
		$(wrapper3).on('keypress','.hora6',validateHour); //para el elemento dentro de destino que tenga la clase "hora", cuando se presione la tecla ejecuta la función validateHour
		$(wrapper3).on('blur','.hora6',formatHour);
		$(wrapper3).on('blur','.hora6',calculardiferencia);
 
});
 
</script>
<!------------------------------------------------------------------------------>
<style type="text/css">
body,td,th {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 12px;
	font-weight: bold;
}
<!---------------------------------------
</style>
<link href="estilos.css" rel="stylesheet" type="text/css" />
<style type="text/css">
#apDiv1 {
	position: absolute;
	left: 134px;
	top: 9px;
	width: 848px;
	height: 87px;
	z-index: 1;
}
	.campos{
		font-size: 11px;
	}
	#viaje_numero {
  width: 2em;
}
</style>
</head>
<body>
<form id="form1" name="form1" method="post" action="enviayprocesa.php">
  <table width="1084" border="0" align="center" cellpadding="0" cellspacing="0">
    <tr>
      <td height="78" colspan="3" bgcolor="#FFFFFF"><a href="salir.php"><img style="float:left; padding-bottom:5px;" src="arribalog.png" width="159" height="72" /></a>
        <div style="padding-top:10px">
          <center>
            fORMULARIO AGREGAR INFORME DE HORAS EXTRAS <br />
          </center>
          <br />
      </div></td>
    </tr>
    <tr>
      <td width="116" height="15" bgcolor="#FF6600"><a href="seleccionformulario.php"><img src="regresar.png" width="115" height="26" /></a></td>
      <td width="866" bgcolor="#FF6600"> </td>
      <td width="115" bgcolor="#FF6600"><a href="salir.php"><img src="salirbtnn.png" width="115" height="26" /></a></td>
    </tr>
    <tr>
      <td height="15" colspan="3" bgcolor="#FFFFFF" style="text-align:right" >Bienvenido <?php echo $_SESSION['nombre'] ?> - Municipio de <?php echo $_SESSION['municipio'] ?></td>
    </tr>
    <tr>
      <td height="220" colspan="3" bgcolor="#FFA466"><table width="1077" border="0" align="center" cellpadding="2" cellspacing="2">
        <tr>
          <td colspan="2"><input name="codigo" type="hidden" id="codigo" value="<? echo $time2 ?>" />
            <input name="municipio" type="hidden" id="municipio" value="<?php echo $_SESSION['municipio'] ?>" />
            <input name="fecha_envio" type="hidden" id="fecha_envio" value=<? echo $fechaActual ?>" /></td>
          <td colspan="3"> </td>
        </tr>
        <tr>
          <td width="77" height="26">Fecha:</td>
          <td width="144"><input name="fecha_reporte" type="date" required id="fecha_reporte" class="campos2"/>
          </td>
          <td width="156">Es dia Festivo
            <input name="festivo" type="checkbox" id="festivo" value="SI" /></td>
          <td width="68"> </td>
          <td width="620"> </td>
        </tr>
        <tr>
          <td height="6" colspan="5"><hr /></td>
        </tr>
        <tr>
          <td colspan="5"><table width="1089" border="0" cellpadding="2" cellspacing="2">
            <tr>
              <td height="28" colspan="3"><div class="field_wrapper3">
                <div>
                       Operario Extra:
                  <select name="operariohoraextra[]" required="required" class="campos selector" id="operarioextra">
                    <option value="">Seleccione:</option>
                    <?php
          $query = $mysqli -> query ("SELECT * FROM operarios_nom WHERE estado='activo' AND municipio='$municcc' ORDER BY nombre ASC");
          while ($valores = mysqli_fetch_array($query)) {
            echo '<option value="'.strtoupper ($valores[nombre]).'">'.strtoupper ($valores[nombre]).'</option>';
          }
        ?>
                  </select>
                  <label> Como: </label><select name="tipohoraextra[]" id="tipohoraextra" required="required" class="campos selector">
                  <option value="">Seleccione</option>
                  <option value="Recolector">Recolector</option>
                  <option value="Escobita">Escobita</option>
                  <option value="Alimentador">Alimentador</option>
                  <option value="Supervisor">Supervisor</option>
                  <option value="Apoyo">Apoyo</option>
                  <option value="Otro">Otro</option>
                  </select>
                  <label>Inicia:</label>
                  <input name="horaextra[]" type="text" required="required" class="hora5" id="horaextra" autocomplete="off" size="2" maxlength="5" />
                  <label>Finaliza:</label>
                  <input name="horaextra2[]" type="text" required="required" class="hora6" id="horaextra2" autocomplete="off" size="2" maxlength="5" onChange="calculardiferencia();"/>-
                  <input name="horaextrat[]" type="text" class="horaextrat" autocomplete="off" size="2" maxlength="5" readonly="readonly"/>
                  </label>
<script>
	document.querySelector('.hora5').addEventListener('keypress',validateHour5);
	document.querySelector('.hora5').addEventListener('blur',formatHour5);
	document.querySelector('.hora6').addEventListener('keypress',validateHour6);
	document.querySelector('.hora6').addEventListener('blur',formatHour6);
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);
			var textNew;
			if ( e.key != ':' || ( e.key == ':' && (textStart+textEnd).search(':') == -1))
			{
				textNew = textStart + e.key + textEnd;
				if ( textNew.search(':') != -1 )
				{
					var aText = textNew.split(':');
					textStart = aText[0];
					textEnd   = aText[1];
					if( textStart<24 && textEnd<60)
					{
						if ( e.key == ':' && textStart.length < 2 )
						{
							if ( textStart.length == 0 )
							{
								position++;
							}
							textStart = textStart.padStart(2, '0');
							position++;
						}
						textNew = textStart + ':' + textEnd;
					}
					else
					{
						return;
					}
				}
				else
				{
					switch( textNew.length )
					{
						case 1:
							break;
						case 2:
							if ( textNew >= 24 )
							{
								textNew = '00:' + textNew;
								position = 4;
							}
							else if ( e.key == ':' )
							{
								textNew = textNew + ':';
								position++;
							}
							break;
						case 3:
							if ( textNew.substr(0, 2) < 24 && textNew.substr(2, 1) < 60 )
							{
								textNew = textNew.substr(0, 2) + ':' + textNew.substr(2, 1);
							}
							else if ( textNew.substr(0, 1) < 24 && textNew.substr(1, 2) < 60)
							{
								textNew = textNew.substr(0, 1).padStart(2, '0') + ':' + textNew.substr(2, 1);
							}
							else
							{
								return;
							}
							position++;
							break;
						case 4:
							if ( textNew.substr(0, 2) < 24 && textNew.substr(2, 2) < 60 )
							{
								textNew = textNew.substr(0, 2) + ':' + textNew.substr(2, 2);
								position++;
							}
							else
							{
								return;
							}
							break;
						default:
							return false;
					}
				}
				if ( textNew.length <= 5 )
				{
					this.value = textNew;
					this.selectionStart = ++position;
					this.selectionEnd   = this.selectionStart;
				}
			}
		}
	}
	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{
				switch (text.length){
					case 1:
					case 2:
						textPart[0] = 0;
						textPart.push(text);
						break;
					case 3:
						if ( text.substr(0, 1)<24 && text.substr(1, 2)<60 )
						{
                        textPart[0] = text.substr(0, 1);
						textPart.push(text.substr(1, 2));
						}else if ( text.substr(0, 2)<24 && text.substr(2, 1)<60)
						{
                        textPart[0] = text.substr(0, 2);
						textPart.push(text.substr(2, 1));
						}
						break;
					case 4:
						textPart[0] = text.substr(0, 2);
						textPart.push(text.substr(2, 2));
						break;
				}
			}
			if ( textPart.length == 2 )
			{
				textPart[0] = String(textPart[0]).padStart(2, '0');
				textPart[1] = String(textPart[1]).padStart(2, '0');
				this.value = textPart.join(':');
			}
			else
			{
				this.value = '';
			}
		}
	}
</script>
<script>
function newDate(partes) {
    var date = new Date(0);
    date.setHours(partes[0]);
    date.setMinutes(partes[1]);
    return date;
}
function prefijo(num) {
    return num < 10 ? ('0' + num) : num;
}
function calculardiferencia(){
  var dateDesde = newDate($('.hora5').val().split(':'));
  var dateHasta = newDate($('.hora6').val().split(':'));
  var minutos = (dateHasta - dateDesde)/1000/60;
  var horas = Math.floor(minutos/60);
  minutos = minutos % 60;
  $('.horaextrat').val(prefijo(horas) + ':' + prefijo(minutos));
}
</script>
<script>
window.addEventListener('load',mostrar);
function mostrar() {
  var x = document.getElementById('alerta');
  if (x.style.display === 'none') {
      x.style.display = 'block';
  } else {
      x.style.display = 'none';
  }
}
</script>
                                    <label>Nota: </label>
                  <input name="observacionesextra[]" type="text" id="observacionesextra" size="14" />
                  </label>Placa:
                  <input name="placa_extra[]" type="text" id="placa_extra" size="5" style="text-transform:uppercase;" onkeyup="javascript:this.value=this.value.toUpperCase();" autocomplete="off"/>
<a href="javascript:void(0);" class="remove_button" title="Borrar Operario de Barrido"></div>
              </div>
                <div></div>
                <a href="javascript:void(0);" class="add_button2" title="Agregar"></a></td>
            </tr>
            <tr>              <td width="175" height="28"> </td>
              <td width="738"> </td>
              <td width="156"><a href="javascript:void(0);" class="add_button3" title="Agregar Operario de Barrido">Agregar Hora Extra <img src="add-icon.png" width="24" height="24"/></a></td>
            </tr>
            <tr>
              <td height="6" colspan="3"><hr /></td>
              </tr>
          </table></td>
          </tr>
        <tr>
          <td colspan="5"><div id="content2" style="display: none;">
            </div></td>
        </tr>
        <tr>
          <td colspan="5"></td>
        </tr>
        <tr>
          <td colspan="5"></td>
        </tr>
        <tr>
          <td colspan="5"><input name="botons" type="submit" class="boton" id="button" value="Grabar" /></td>
        </tr>
        <tr>
          <td height="19" colspan="5"> </td>
        </tr>
      </table></td>
    </tr>
    <tr>
      <td height="26" colspan="3" bgcolor="#FF6600"> </td>
    </tr>
  </table>
</form>
<div id="resultadoBusqueda"></div>
<p> </p>
<p> </p>
<p> </p>
</body>
</html>
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de Alejandro
Val: 1.448
Plata
Ha mantenido su posición en JavaScript (en relación al último mes)
Gráfica de JavaScript

Me repite el mismo valor en campos siguientes.. Ayuda Por fa

Publicado por Alejandro (532 intervenciones) el 16/11/2022 00:22:12
  • Alejandro se encuentra ahora conectado en el
  • chat de PHP
1
2
3
4
5
6
7
8
function calculardiferencia(){
	var dateDesde = newDate( $(this).closest('div').find('.hora5').val().split(':') );
	var dateHasta = newDate( $(this).closest('div').find('.hora6').val().split(':') );
	var minutos = (dateHasta - dateDesde)/1000/60;
	var horas = Math.floor(minutos/60);
	minutos = minutos % 60;
	$(this).closest('div').find('.horaextrat').val( prefijo(horas) + ':' + prefijo(minutos) );
}
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de Eduardo Arroyo
Val: 159
Ha mantenido su posición en JavaScript (en relación al último mes)
Gráfica de JavaScript

Me repite el mismo valor en campos siguientes.. Ayuda Por fa

Publicado por Eduardo Arroyo (176 intervenciones) el 16/11/2022 01:02:32
Hola Alejrandro mil gracias por responder.. lo he puesto pero no me resulta cambie el codigo de la funcion calculardiferencia() asi como me lo pasas pero no me resulta ahora el calculo... estaré omitiendo algo???
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de Alejandro
Val: 1.448
Plata
Ha mantenido su posición en JavaScript (en relación al último mes)
Gráfica de JavaScript

Me repite el mismo valor en campos siguientes.. Ayuda Por fa

Publicado por Alejandro (532 intervenciones) el 16/11/2022 16:48:48
  • Alejandro se encuentra ahora conectado en el
  • chat de PHP
No se trata de copiar y pegar ya que como no estoy corriendo el código no tengo la certeza de que funcione.
Se trata de comprensión:
$(this) es el elemento que dispara la función.
.closest('div') es el elemento div padre mas próximo de $(this), equivale a la fila.
.find('.hora5') busca el elemento con la clase .hora5 unicamente en la fila.

Si el calculo te da valor erróneo, verifica tus formulas.
Si la función no corre, verifica el inspector, utiliza console.log() para hacer un seguimiento de lo que ocurre en la función.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar