formulario con campos dinámicos con calculo de horas

  • Autor Autor ewaldo22
  • Fecha de inicio Fecha de inicio
E

ewaldo22

Curioso
¡Usuario con pocos negocios! ¡Utiliza siempre saldo de Forobeta!
hola a todos tengo el siguiente script que no he podido terminar.. y espero me puedan por favor ayudar...

tengo un formulario el cual agrega campos para así almacenar de un solo varios datos..

1688049063568.png


pero existe un campo el cual calcula la diferencia de 2 horas que se van agregando..

1688049150713.png



lo que sucede es que al ir agregando campos los otros campos (agregados) toman el calculo del primero (cuando hago blur en el primero) y así sucesivamente.. lo que quiero es que ese calculo sea independiente para cada juego de campos...

1688049251279.png


acá pongo el código

Insertar CODE, HTML o PHP:
<?php include("seguridad.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</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'];
$nombrepqr=$_SESSION['nombre'];
$quien=$_SESSION['tipo'];
?>
<?php
$fechaActual = date('Y-m-d H:i:s');
  $mysqli = new mysqli('localhost', 'usuario', 'claveeee', 'gggggg');
  ?>
       <?php


     $connection = mysql_connect("localhost", "userrrrr", "contrasena");
    mysql_select_db("bdddd", $connection);
     $result = mysql_query("SELECT * FROM operarios_nom WHERE estado='activo'", $connection);
    //$result = mysql_query("SELECT * FROM operarios_nom WHERE estado='activo' AND ciudad='ACA LA VARIABLE GLOBAL DE SESSION CIUDAD' ", $connection);
    $array = array();
    if($result){
        while ($row = mysql_fetch_array($result)) {
            $equipo = utf8_encode(strtoupper ($row['nombre']));
            array_push($array, $equipo); // equipos
        }
    }
?>
<!-------------------------EXTRAS------------------------------------->
<script>
var fieldHTML3 = '<div id="destino2">&nbsp;&nbsp;&nbsp;<label> Operario Extra en Relleno: </label><select name="operariohoraextra[]" required="required" class="campos selector" id="operariohoraextra"><option value="">Seleccione:</option><?php $query = $mysqli -> query ("SELECT * FROM datos_archivo WHERE cargo IN ('AUXILIAR RELLENO','SUPERVISOR RELLENO','OPERARIO BULLDOZER','OPERARIO MAQUINARIA PESADA','CELADOR') AND estadotrabajador='ACTIVO' 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="Auxiliar de Relleno">Auxiliar de Relleno</option><option value="Operador Maquinaria Pesada">Operador Maquinaria Pesada</option><option value="Conductor Relleno">Conductor Relleno</option></select><label> <label>Hora Inicia: </label><input name="horaextra1[]" type="text" required="required" class="hora5" id="horaextra2" autocomplete="off" size="2" maxlength="5" onBlur="calculardiferencia();"/><label> Hora Finaliza: </label><input name="horaextra2[]" type="text" required="required" class="hora6" id="horaextra3" autocomplete="off" size="2" maxlength="5"/> Total Horas Extras: <input name="horaextrat[]" style="color: #ff0000;"  type="text" class="horaextrat" autocomplete="off" size="2" maxlength="5" readonly="readonly"/></label> <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);
        $(wrapper3).on('blur','.hora5',formatHour);
        $(wrapper3).on('keypress','.hora6',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="procesa.php" onsubmit="this.botons.disabled=true">
  <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 RELLENO<br />
          </center>
          <br />
      </div></td>
    </tr>
    <tr>
      <td width="116" height="15" bgcolor="#FF6600">
      <?php
       if ($quien=="admin"){
         echo  '<a href="seleccionformulario.php"><img src="regresar.png" width="115" height="26" /></a>';
       }else{
          echo  '<a href="index.php"><img src="regresar.png" width="115" height="26" /></a>';
       }         
      ?>   
      </td>
      <td width="866" bgcolor="#FF6600">&nbsp;</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 $nombrepqr ?> - Municipio de <?php echo $municcc ?></td>
    </tr>
    <tr>
      <td height="220" colspan="3" bgcolor="#FFA466"><table width="1244" 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="Relleno" />
            <input name="fecha_envio" type="hidden" id="fecha_envio" value=<? echo $fechaActual ?>" /></td>
          <td colspan="3">&nbsp;</td>
        </tr>
        <tr>
          <td width="72" height="26">Fecha:</td>
          <td width="149"><input name="fecha_reporte" type="date" required id="fecha_reporte" class="campos2"/>   
          </td>
          <td width="153">Es dia Festivo
            <input name="festivo" type="checkbox" id="festivo" value="SI" /></td>
          <td width="62">&nbsp;</td>
          <td width="776">&nbsp;</td>
        </tr>
        <tr>
          <td height="6" colspan="5"><hr /></td>
        </tr>
        <tr>
          <td colspan="5"><table width="1244" border="0" cellpadding="2" cellspacing="2">
            <tr>
              <td height="28" colspan="3"><div class="field_wrapper3">
                <div>
                   &nbsp;&nbsp;&nbsp;&nbsp;Operario Extra en Relleno:
                   <select name="operariohoraextra[]" required="required" class="campos selector" id="operarioextra">
                    <option value="">Seleccione:</option>
                    <?php


          $query = $mysqli -> query ("SELECT * FROM datos_archivo WHERE cargo IN ('AUXILIAR RELLENO','SUPERVISOR RELLENO','OPERARIO BULLDOZER','OPERARIO MAQUINARIA PESADA','CELADOR') AND estadotrabajador='ACTIVO' 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="Auxiliar de Relleno">Auxiliar de Relleno</option>
                  <option value="Operador Maquinaria Pesada">Operador Maquinaria Pesada</option>
                  <option value="Conductor Relleno">Conductor Relleno</option>
                  </select>
                  Hora
                  <label>Inicia: </label>
                  <input name="horaextra1[]" type="text" required="required" class="hora5" id="horaextra2" autocomplete="off" size="2" maxlength="5" onBlur="calculardiferencia();"/>
                  Hora
                  <label>Finaliza:</label>
                  <input name="horaextra2[]" type="text" required="required" class="hora6" id="horaextra3" autocomplete="off" size="2" maxlength="5" onBlur="calculardiferencia();"/>
                  <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>Total Horas Extras:
<input name="horaextrat[]" style="color: #ff0000;"  type="text" class="horaextrat" autocomplete="off" size="2" maxlength="5" readonly="readonly"/>
</label>
                </div>
              </div>
                <div></div>
                <a href="javascript:void(0);" class="add_button2" title="Agregar"></a></td>
            </tr>
            <tr>              <td width="175" height="28">&nbsp;</td>
              <td width="915">&nbsp;</td>
              <td width="134"><a href="javascript:void(0);" class="add_button3" title="Agregar Operario de Saneamiento">Agregar Otro </a><a href="javascript:void(0);" class="add_button3" title="Agregar Operario de Saneamiento"><img src="add-icon.png" width="21" height="21" /></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">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;            <input name="botons" type="submit" class="boton" id="button" value="Grabar" /></td>
        </tr>
        <tr>
          <td height="19" colspan="5">&nbsp;</td>
        </tr>
      </table></td>
    </tr>
    <tr>
      <td height="26" colspan="3" bgcolor="#FF6600">&nbsp;</td>
    </tr>
  </table>
</form>
<div id="resultadoBusqueda"></div>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
</body>
</html>
 
Última edición:
El codigo deberia ir algo asi
JavaScript:
onBlur="calculardiferencia('horasextra1')"


function calculardiferencia(campo){
  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;
 
  $('.'+campo).val(prefijo(horas) + ':' + prefijo(minutos));
}
 
Hola HeisenberDev mil gracias por responder...

pues te cuento que le hice los cambios que me sugeriste.. pero ahora no aparece en el campo (horaextrat) donde van saliendo el calculo de las horas el valor...

1688055534424.webp


puse en la funcion que me sugieres el nombre del campo pero no aparece aun asi

Insertar CODE, HTML o PHP:
$('.'+horaextrat).val(prefijo(horas) + ':' + prefijo(minutos));

de todas maneras aca pongo todo el codigo con las modificaciones que me sugieres para ver en que lado cometí algún error...

JavaScript:
<?php include("seguridad.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</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'];
$nombrepqr=$_SESSION['nombre'];
$quien=$_SESSION['tipo'];
?>
<?php
$fechaActual = date('Y-m-d H:i:s');
  $mysqli = new mysqli('localhost', 'usuario', 'contrasena', 'bd');
  ?>
       <?php


     $connection = mysql_connect("localhost", "usuariooo", "contrasenaaa");
    mysql_select_db("bdbbb", $connection);
     $result = mysql_query("SELECT * FROM operarios_nom WHERE estado='activo'", $connection);
    //$result = mysql_query("SELECT * FROM operarios_nom WHERE estado='activo' AND ciudad='ACA LA VARIABLE GLOBAL DE SESSION CIUDAD' ", $connection);
    $array = array();
    if($result){
        while ($row = mysql_fetch_array($result)) {
            $equipo = utf8_encode(strtoupper ($row['nombre']));
            array_push($array, $equipo); // equipos
        }
    }
?>
<!-------------------------EXTRAS------------------------------------->
<script>
var fieldHTML3 = '<div id="destino2">&nbsp;&nbsp;&nbsp;<label> Operario Extra en Relleno: </label><select name="operariohoraextra[]" required="required" class="campos selector" id="operariohoraextra"><option value="">Seleccione:</option><?php $query = $mysqli -> query ("SELECT * FROM datos_archivo WHERE cargo IN ('AUXILIAR RELLENO','SUPERVISOR RELLENO','OPERARIO BULLDOZER','OPERARIO MAQUINARIA PESADA','CELADOR') AND estadotrabajador='ACTIVO' 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="Auxiliar de Relleno">Auxiliar de Relleno</option><option value="Operador Maquinaria Pesada">Operador Maquinaria Pesada</option><option value="Conductor Relleno">Conductor Relleno</option></select><label> <label>Hora Inicia: </label><input name="horaextra1[]" type="text" required="required" class="hora5" id="horaextra2" autocomplete="off" size="2" maxlength="5" onBlur="calculardiferencia(horasextra1);"/><label> Hora Finaliza: </label><input name="horaextra2[]" type="text" required="required" class="hora6" id="horaextra3" autocomplete="off" size="2" maxlength="5" onBlur="calculardiferencia(horasextra2);"/> Total Horas Extras: <input name="horaextrat[]" style="color: #ff0000;"  type="text" class="horaextrat" autocomplete="off" size="2" maxlength="5" readonly="readonly"/></label> <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();
            //$('.hora5').calculardiferencia();
            //$('.hora6').calculardiferencia();
          
        }
            });
    $(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);
        $(wrapper3).on('blur','.hora5',formatHour);
        $(wrapper3).on('keypress','.hora6',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="procesa.php" onsubmit="this.botons.disabled=true">
  <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 RELLENO<br />
          </center>
          <br />
      </div></td>
    </tr>
    <tr>
      <td width="116" height="15" bgcolor="#FF6600">
      <?php
       if ($quien=="admin"){
         echo  '<a href="seleccionformulario.php"><img src="regresar.png" width="115" height="26" /></a>';
       }else{
          echo  '<a href="index.php"><img src="regresar.png" width="115" height="26" /></a>';
       }         
      ?>   
      </td>
      <td width="866" bgcolor="#FF6600">&nbsp;</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 $nombrepqr ?> - Municipio de <?php echo $municcc ?></td>
    </tr>
    <tr>
      <td height="220" colspan="3" bgcolor="#FFA466"><table width="1244" 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="Relleno" />
            <input name="fecha_envio" type="hidden" id="fecha_envio" value=<? echo $fechaActual ?>" /></td>
          <td colspan="3">&nbsp;</td>
        </tr>
        <tr>
          <td width="72" height="26">Fecha:</td>
          <td width="149"><input name="fecha_reporte" type="date" required id="fecha_reporte" class="campos2"/>   
          </td>
          <td width="153">Es dia Festivo
            <input name="festivo" type="checkbox" id="festivo" value="SI" /></td>
          <td width="62">&nbsp;</td>
          <td width="776">&nbsp;</td>
        </tr>
        <tr>
          <td height="6" colspan="5"><hr /></td>
        </tr>
        <tr>
          <td colspan="5"><table width="1244" border="0" cellpadding="2" cellspacing="2">
            <tr>
              <td height="28" colspan="3"><div class="field_wrapper3">
                <div>
                   &nbsp;&nbsp;&nbsp;&nbsp;Operario Extra en Relleno:
                   <select name="operariohoraextra[]" required="required" class="campos selector" id="operarioextra">
                    <option value="">Seleccione:</option>
                    <?php


          $query = $mysqli -> query ("SELECT * FROM datos_archivo WHERE cargo IN ('AUXILIAR RELLENO','SUPERVISOR RELLENO','OPERARIO BULLDOZER','OPERARIO MAQUINARIA PESADA','CELADOR') AND estadotrabajador='ACTIVO' 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="Auxiliar de Relleno">Auxiliar de Relleno</option>
                  <option value="Operador Maquinaria Pesada">Operador Maquinaria Pesada</option>
                  <option value="Conductor Relleno">Conductor Relleno</option>
                  </select>
                  Hora
                  <label>Inicia: </label>
                  <input name="horaextra1[]" type="text" required="required" class="hora5" id="horaextra2" autocomplete="off" size="2" maxlength="5" onBlur="calculardiferencia(horasextra1);"/>
                  Hora
                  <label>Finaliza:</label>
                  <input name="horaextra2[]" type="text" required="required" class="hora6" id="horaextra3" autocomplete="off" size="2" maxlength="5" onBlur="calculardiferencia(horasextra2);"/>
                  <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(campo){
  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>Total Horas Extras:
<input name="horaextrat[]" style="color: #ff0000;"  type="text" class="horaextrat" autocomplete="off" size="2" maxlength="5" readonly="readonly"/>
</label>
                </div>
              </div>
                <div></div>
                <a href="javascript:void(0);" class="add_button2" title="Agregar"></a></td>
            </tr>
            <tr>              <td width="175" height="28">&nbsp;</td>
              <td width="915">&nbsp;</td>
              <td width="134"><a href="javascript:void(0);" class="add_button3" title="Agregar Operario de Saneamiento">Agregar Otro </a><a href="javascript:void(0);" class="add_button3" title="Agregar Operario de Saneamiento"><img src="add-icon.png" width="21" height="21" /></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">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;            <input name="botons" type="submit" class="boton" id="button" value="Grabar" /></td>
        </tr>
        <tr>
          <td height="19" colspan="5">&nbsp;</td>
        </tr>
      </table></td>
    </tr>
    <tr>
      <td height="26" colspan="3" bgcolor="#FF6600">&nbsp;</td>
    </tr>
  </table>
</form>
<div id="resultadoBusqueda"></div>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
</body>
</html>
 
a ver la variable de "campo" es el nombre de una clase que deberias darle al tercer campo de .horasextras , deberia tener cada campo clase diferente como .horasextra1 , .horasextra2 , .horasextra3 para saber luego desde la funcion cual input calcular y cual input de horas extras es el indicado.​
 
aaa!!! entiendo... yo le tengo a ese campo la case (class="horaextrat") ¿existe algún problema si le dejo esa misma class para que funcione???

por eso le puse esta parte así.. pero aun no funciona

JavaScript:
$('.'+horaextrat).val(prefijo(horas) + ':' + prefijo(minutos));

mil gracias por tu ayuda!!!
 
Última edición:
aaa!!! entiendo... yo le tengo a ese campo la case (class="horaextrat") ¿existe algún problema si le dejo esa misma class???

por eso le puse esta parte asi

JavaScript:
$('.'+horaextrat).val(prefijo(horas) + ':' + prefijo(minutos));

mil gracias por tu ayuda!!!
No puede tener la misma clase, debe variar para que se le asigne esa hora al campo correcto, como todas tienen esa misma clase pasa el problema, que se le asigna la misma hora a todos esos campos
 
No puede tener la misma clase, debe variar para que se le asigne esa hora al campo correcto, como todas tienen esa misma clase pasa el problema, que se le asigna la misma hora a todos esos campos

es correcto, pero como son campos que se van agregando con un botón.. como diferencio cada uno que se va creando dinámicamente pues se van creando...
ademas le puse la clase campo al tercer campo asi como indicas y aun no me muestra el calculo de las horas...

JavaScript:
<input name="horaextrat[]" style="color: #ff0000;"  type="text" class="campo" autocomplete="off" size="2" maxlength="5" readonly="readonly"/>

1688057093256.png
 
Última edición:
Puedes agregarle la clase con jquery luego de generar los campos con este codigo :
JavaScript:
$(".horaextra").each(function(a,b){
    $(this).addClass("horaextra"+a)
})
 
Atrás
Arriba