JQuery - Solo funciona en primer juego de campos y no en los agregados... Ayuda!!

 
Vista:
Imágen de perfil de Eduardo Arroyo Teherán

Solo funciona en primer juego de campos y no en los agregados... Ayuda!!

Publicado por Eduardo Arroyo Teherán (16 intervenciones) el 05/08/2023 17:11:35
Hola a todos espero me puedan ayudar hace poco realice este ejemplo de formularios que se adicionan o clonan para crear varios juegos de campos, el input o campo llamado cedula es un campo que hace una comprobación si hay algún dato allí ingresado ya existe en la base de datos, para evitar duplicados, si lo hay muestra una X roja al lado de este campo, pero NO entiendo por que solo me funciona en el primer juego de campos y en los que se crean, adicionan o clonan No he usado clases para evitar las ID ya q estas son únicas y así no entrar en conflictos.. he revisado este articulo pues en ese articulo https://es.stackoverflow.com/questions/364918/operaciones-con-campos-dinamicos-con-jquery-al-clonar pasa algo parecido a lo que me sucede en este ejemplo.

Aca pongo el Código que uso (la función que hace tal comprobación esta al final. el cual en tiempo real busca mediante un archivo php ComprobarDisponibilidad.php que no exista el numero de identificación (cedula Repetido)

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
<?php include("seguridad.php");
header('Content-Type: text/html; charset=UTF-8');
?>
<link rel="shortcut icon" href="icono.png">
<!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>
<title>Planilla Votantes</title>
<link rel="stylesheet" type="text/css" href="css/select2.css">
<script src="jquery-3.1.1.min.js"></script>
<script src="js/select2.js"></script>
<script>
jQuery(document).ready(function($){
    $(document).ready(function() {
        $('.selector').select2();
    });
});
</script>
<?php
  $mysqli = new mysqli('localhost', 'root', '', 'basededatosnombre');
 $mysqli->set_charset("utf8");
  ?>
<!--------------SCRIPT PARA PRIMER JUEGO DE FORMULARIOS ESTE ESTA LISTO--------------------->
<script type="text/javascript">
	$(document).ready(function(){
		var maxField = 10; //Input fields increment limitation
		var addButton = $('.add_button'); //Add button selector
		var wrapper = $('.field_wrapper'); //Input field wrapper
		//name="hora1" type="text" autofocus="autofocus" class="hora1" id="hora1" size="5"
				//New input field html
		var x = 1; //Initial field counter is 1
		$(addButton).click(function(){ //Once add button is clicked
			if(x < maxField){ //Check maximum number of input fields
				x++; //Increment field counter
				$(wrapper).append(fieldHTML); // Add field html.
			}
		});
		$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
			e.preventDefault();
			$(this).parent('div').remove(); //Remove field html
			x--; //Decrement field counter
		});
		$(wrapper).on('keypress','.hora1',validateHour); //para el elemento dentro de destino que tenga la clase "hora", cuando se presione la tecla ejecuta la función validateHour
		$(wrapper).on('blur','.hora1',formatHour);
		$(wrapper).on('keypress','.hora2',validateHour); //para el elemento dentro de destino que tenga la clase "hora", cuando se presione la tecla ejecuta la función validateHour
		$(wrapper).on('blur','.hora2',formatHour);
	});
////-----------------------PARA LOS CAMPOS HIJOS--------------------------------
	    $(document).ready(function(){
	var maxField2 = 14; //
    var addButton2 = $('.add_button2'); //agrega
    var wrapper2 = $('.field_wrapper2'); //wrapper
	var x = 1; //Initial field counter is 1
    $(addButton2).click(function(){ //Once add button is clicked
        if(x < maxField2){ //Check maximum number of input fields
		    x++; //Increment field counter
            $(wrapper2).append(fieldHTML2); // Add field html
			/// POR FINNNNNNNNNNNNNNNNNNNN
			$('.selector').select2();
 
		 }
    });
    $(wrapper2).on('click', '.remove_button', function(e){ //Once remove button is clicked
        e.preventDefault();
        $(this).parent('div').remove(); //Remove field html
        x--; //Decrement field counter
    });
});
function noPuntoComa( event ) {
 
    var e = event || window.event;
    var key = e.keyCode || e.which;
 
    if ( key === 110 || key === 190 || key === 188 ) {
 
       e.preventDefault();
    }
}
<!----------------------------PARTE---------------------------------------------------->
 var fieldHTML2 = '<div id="destino2"><div class="field_wrapper2"><div><hr>Nombres y Apellidos : <input name="nombreyapellidos[]" required="required" type="text" tabindex="2" size="30" style="text-transform:uppercase;" onkeyup="javascript:this.value=this.value.toUpperCase(); "/><label> Cédula: </label><input name="cedula[]" type="number" tabindex="3" required="required" onBlur="comprobarUsuario()" class="ced"  size="10" style="width:99px"/><span class="estadousuario"></span><label> Municipio/Correg: </label><select name="municipio[]" required="required" tabindex="4" class="campos selector" style="width:130px"><option value="">Seleccione:</option><?php $query_mpio = $mysqli -> query ("SELECT * FROM municipio_votantes ORDER BY munic_votantes ASC");while ($valores_mpio = mysqli_fetch_array($query_mpio)) {echo '<option value="'.strtoupper ($valores_mpio[munic_votantes]).'">'.strtoupper ($valores_mpio[munic_votantes]).'</option>';}?></select> Lugar de Votación: <select name="puesto[]" required="required" class="campos selector" tabindex="5" style="width:130px"><option value="">Seleccione:</option><?php $query_lugar = $mysqli -> query ("SELECT * FROM lugar_votantes ORDER BY lugar_votaciones ASC");while ($valores_lugar = mysqli_fetch_array($query_lugar)) {echo '<option value="'.strtoupper ($valores_lugar[lugar_votaciones]).'">'.strtoupper ($valores_lugar[lugar_votaciones]).'</option>';
}?></select> Mesa: <input name="mesa[]" type="number" tabindex="6" style="width:50px" size="2" required="required"/> <a href="javascript:void(0);" class="remove_button" title="Borrar"><img src="remove-icon.png" width="20" height="20"/></a></div>'; //New input field html
  </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>
<style type="text/css">
  .boton{
        font-size:12px;
        font-family:Verdana,Helvetica;
        font-weight:bold;
        color:white;
        background:#282859;
        border:0px;
        width:110px;
        height:30px;
       }
a:link {
	color: #282859;
	text-decoration: none;
}
a:visited {
	text-decoration: none;
	color: #282859;
}
a:hover {
	text-decoration: none;
	color: #282859;
}
a:active {
	text-decoration: none;
	color: #282859;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<form id="form1" name="form1" method="post" action="procesa.php">
  <table width="90%" border="0" align="center" cellpadding="0" cellspacing="0">
    <tr>
      <td width="115" height="15" bgcolor="#282859"><a href="index.php"><img src="regresar.png" width="115" height="26" /></a></td>
      <td width="1054" bgcolor="#282859"> </td>
      <td width="115" bgcolor="#282859"><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 utf8_encode($_SESSION['nombre_usuario']) ?></td>
    </tr>
    <tr>
      <td height="220" colspan="3" bgcolor="#EFEFEF"><table width="98%" border="0" align="center" cellpadding="2" cellspacing="2">
        <tr>
          <td width="198" bgcolor="#EFEFEF"> </td>
          <td width="934" colspan="3" bgcolor="#EFEFEF"> </td>
        </tr>
        <tr>
          <td height="26" colspan="4" bgcolor="#EFEFEF">
            Lider:
            <select name="lider" autofocus required="required" tabindex="1" class="campos selector">
              <option value="">Seleccione:</option>
              <?php $query = $mysqli -> query ("SELECT * FROM lider_votantes WHERE estado_lider='activo' ORDER BY nombre_lider ASC");
          while ($valores = mysqli_fetch_array($query)) {
			  echo '<option value="'.strtoupper ($valores[nombre_lider]).'">'.strtoupper ($valores[nombre_lider]).'</option>';
          }
		  ?>
            </select></td>
          </tr>
        <tr>
          <td height="6" colspan="4" bgcolor="#EFEFEF"><hr /></td>
        </tr>
        <tr>
          <td colspan="4" bgcolor="#EFEFEF">
          <table width="99%" border="0" align="center" cellpadding="2" cellspacing="2">
            <tr>
              <td><div class="field_wrapper2">
                <div>Nombres y Apellidos :
                   <input name="nombreyapellidos[]" type="text" id="nombreyapellidos" size="30"  required="required" style="text-transform:uppercase;" tabindex="2" onKeyUp="javascript:this.value=this.value.toUpperCase();"/>
                   <label>Cédula: </label>
                     <input name="cedula[]" tabindex="3" type="number" class="ced" onBlur="comprobarUsuario()" required size="10" style="width:99px"/><span class="estadousuario"></span>
                     <label>Municipio/Correg: </label>
                     <select name="municipio[]" required="required" tabindex="4" class="campos selector" style="width:130px">
                       <option value="">Seleccione:</option>
                       <?php $query_mpio = $mysqli -> query ("SELECT * FROM municipio_votantes ORDER BY munic_votantes ASC");
          while ($valores_mpio = mysqli_fetch_array($query_mpio)) {echo '<option value="'.strtoupper ($valores_mpio[munic_votantes]).'">'.strtoupper ($valores_mpio[munic_votantes]).'</option>';
          }
		  ?>
                     </select>
                     Lugar de Votación:
<select name="puesto[]" required="required" class="campos selector" tabindex="5" style="width:130px">
                       <option value="">Seleccione:</option>
                       <?php $query_lugar = $mysqli -> query ("SELECT * FROM lugar_votantes ORDER BY lugar_votaciones ASC");
          while ($valores_lugar = mysqli_fetch_array($query_lugar)) {echo '<option value="'.strtoupper ($valores_lugar[lugar_votaciones]).'">'.strtoupper ($valores_lugar[lugar_votaciones]).'</option>';
          }
		  ?>
                     </select>
Mesa:
<input name="mesa[]" type="number" tabindex="6" size="2" required style="width:50px"/>
                </div>
                </div><div></div>
                  <a href="javascript:void(0);" class="add_button2" title="Add field"></a></td>
            </tr>
            <tr>
              <td><a style="float:right; padding-right:15px;" tabindex="7" href="javascript:void(0);" class="add_button2" title="Agregar Operario de Saneamiento">Agregar Otro <img src="add-icon.png" width="21" height="21" /></a></td>
              </tr>
            <tr>
              <td><hr /></td>
            </tr>
            </table></td>
          </tr>
        <tr>
          <td colspan="4" bgcolor="#EFEFEF"><div id="content2" style="display: none;">
            </div></td>
        </tr>
        <tr>
          <td colspan="4" bgcolor="#EFEFEF"></td>
        </tr>
        <tr>
          <td colspan="4" bgcolor="#EFEFEF"></td>
        </tr>
        <tr>
          <td colspan="4" bgcolor="#EFEFEF"><input tabindex="8" name="botons" type="submit" class="boton" id="button" value="Grabar Lista" /></td>
        </tr>
        <tr>
          <td height="19" colspan="4" bgcolor="#EFEFEF"> </td>
        </tr>
      </table></td>
    </tr>
    <tr>
      <td height="26" colspan="3" bgcolor="#282859"> </td>
    </tr>
  </table>
</form>
<p> </p>
<p> </p>
<p> </p>
</body>
<script>
function comprobarUsuario() {
	//$("#loaderIcon").show();
	jQuery.ajax({
	//var cedula2 = $(this).find('input[name^="cedula"]').val();
	url: "ComprobarDisponibilidad.php",
	data:'usuario='+$(".ced").val(),
	//data:'usuario='+cedula2;
	type: "POST",
	success:function(data){
		$(".estadousuario").html(data);
		//$("#loaderIcon").hide();
	},
	error:function (){}
	});
}
</script>
</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

Solo funciona en primer juego de campos y no en los agregados... Ayuda!!

Publicado por Alejandro (15 intervenciones) el 25/08/2023 17:45:08
  • Alejandro se encuentra ahora conectado en el
  • chat de PHP
Ya se te había respondido en el post boton para remover o quitar juego de campos...

Tienes código duplicado.
No existen los elementos add_button, field_wrapper2,
La variable fieldHTML no esta definida.
Estas agregando los elementos dentro del existente
1
2
<td><div class="field_wrapper2">......
    <div id="destino2"><div class="field_wrapper2">.....

Por último, sobre tu problema, en teoría te asignaría el data a todos los elementos "estadousuario" ya que no estas especificando uno en concreto.
1
$(".estadousuario").html(data);
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