JavaScript - funcion no funciona dentro de field_wrapper

 
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

funcion no funciona dentro de field_wrapper

Publicado por Eduardo (176 intervenciones) el 18/09/2022 01:30:00
hola a todos tengo al siguiente consulta que no he podido resolver

tengo el siguiente formulario

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<table width="448" border="0" cellpadding="0" cellspacing="0">
    <tr>
      <td width="123"><input name="repuesto_repuesto[]" type="text"  class="form-control-file" id="repuesto_repuesto" size="20"/></td>
      <td width="32"><input onChange="calc()" name="cantidad_repuesto[]" type="text"  class="form-control-file" id="cantidad_repuesto" size="2"/><input id="select" type="hidden" value="*"></td>
      <td width="89"><input name="proveedor_repuesto[]" type="text"  class="form-control-file" id="proveedor_repuesto" size="14"/></td>
      <td width="80"><input name="nitproveedor_repuesto[]" type="text"  class="form-control-file" id="nitproveedor_repuesto" size="12"/></td>
      <td width="75"><input onChange="calc()" name="valoruni_repuesto[]" type="text"  class="form-control-file" id="valoruni_repuesto" size="8"/></td>
      <td width="49"><input name="valortotal_repuesto[]" type="text"  class="form-control-file" id="valortotal_repuesto" size="8"/>
     </td>
      </tr>
  </table>
                </div>
              </div>
            <a href="javascript:void(0);" style='color:blue' class="add_button"><span class="kk">+ Repuesto</span></a></td>
          </tr>

que es un simple formulario con la partucularidad que trae consigo un boton para adicionar juego de campos de manera dinamica.

ahora bien para lograr adicionar estos campos se llama a esta funcion js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<script type="text/javascript">
$(document).ready(function(){
    var maxField = 20; //Input fields increment limitation
    var addButton = $('.add_button'); //Add button selector
    var wrapper = $('.field_wrapper'); //Input field wrapper
    var fieldHTML = '<div><table width="459" border="0" cellpadding="0" cellspacing="0"><tr><td width="123"><input name="repuesto_repuesto[]" type="text"  class="form-control-file" id="repuesto_repuesto" size="20"/></td><td width="32"><input onChange="calc()" name="cantidad_repuesto[]" type="text"  class="form-control-file" id="cantidad_repuesto" size="2"/><input id="select" type="hidden" value="*"></td><td width="89"><input name="proveedor_repuesto[]" type="text"  class="form-control-file" id="proveedor_repuesto" size="14"/></td><td width="80"><input name="nitproveedor_repuesto[]" type="text"  class="form-control-file" id="nitproveedor_repuesto" size="12"/></td><td width="75"><input  onChange="calc()" name="valoruni_repuesto[]" type="text"  class="form-control-file" id="valoruni_repuesto" size="8"/></td><td width="60"><input name="valortotal_repuesto[]" type="text"  class="form-control-file" id="valortotal_repuesto" size="8"/></td><a href="javascript:void(0);" style="color: blue; float:right;" class="remove_button" title="Remove field">X</a></table></div>'; //New input field html
    var x = 1; $(addButton).click(function(){
        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
    });
});
</script>

en eso no tengo problema el promebla es que si se fijan en los campos del formulario que esta tiene un elemento que va multiplicando los campos es decir llama a esta funcion js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script>
function calc() {
var cantidad_repuesto = document.getElementById("cantidad_repuesto").value;
var valoruni_repuesto = document.getElementById("valoruni_repuesto").value;
 
var select = document.getElementById("select").value;
 
var valortotal_repuesto = document.getElementById("valortotal_repuesto");
 
 
valortotal_repuesto.value = parseInt(cantidad_repuesto) * parseInt(valoruni_repuesto);
 
}
</script>

y funciona perfecto en los primeros de campos que aparecen no dinamicos... hace la multiplicacion sin problemas

el problema es que esta no funciona en el segundo juego de campos creado o en los siguientes crerados dinamicamente... he puesto la funcion calc dentro del script y nada no se como hacer paar que alli tambien funcione..

mil gracias
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 algoritmo
Val: 37
Ha aumentado su posición en 2 puestos en JavaScript (en relación al último mes)
Gráfica de JavaScript

funcion no funciona dentro de field_wrapper

Publicado por algoritmo (14 intervenciones) el 18/09/2022 17:47:45
Hola

No puedes crear varios objetos con el mismo 'id'

Espero que sirva, un saludo :)
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
Val: 159
Ha mantenido su posición en JavaScript (en relación al último mes)
Gráfica de JavaScript

funcion no funciona dentro de field_wrapper

Publicado por Eduardo (176 intervenciones) el 19/09/2022 15:54:37
bueno ya hice lso cambios que me explicas cambie el

document.getElementById

por

document.getElementsByClassName

dentro de la función multiplicar y le cambie a los campos del formulario el nombre de los Id asiggnandoselos a los class pero ahora no me funciona ni en el primer juego de campos del formulario no hace la multiplicacion


aca pongo el codigo completo ayudaaa!!!

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
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Serviaseo S.A</title>
<link rel="stylesheet" type="text/css" href="../css/select2.css">
<style type="text/css">
body,td,th {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 12px;
	font-weight: bold;
	text-align: left;
}
body {
	margin-left: 0px;
	margin-top: 0px;
	margin-right: 0px;
	margin-bottom: 0px;
}
.kk {	font-size: 14px;
}
a:link {
	text-decoration: none;
}
a:visited {
	text-decoration: none;
}
a:hover {
	text-decoration: none;
}
a:active {
	text-decoration: none;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.1.js" integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI=" crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
jQuery(document).ready(function($){
    $(document).ready(function() {
        $('.selector').select2();
    });
});
</script>
<script>
function multiplicar(){
	   m1 =document.getElementsByClassName("multiplicando").value;
	   m2 =document.getElementsByClassName("multiplicador").value;
	//m1 = document.getElementById("multiplicando").value;
	//m2 = document.getElementById("multiplicador").value;
	r = m1*m2;
	//document.getElementById("resultado").value = r;
	document.getElementsByClassName("resultado").value= r;
	}
</script>
<script>
var parametro;
function popupnit()
{
<!----parametro2 = window.open("ventana_buscar.php","","width=400,height=300,top=146,left=459,directories=no, status=no, menubar=no,toolbar=no");--->
parametro = window.open("ventana_buscarproveedor.php","","width=400,height=300,top=146,left=459,directories=no, status=no, menubar=no,toolbar=no");
parametro.document.getElementById('1').value = "nombre_provvedor" ;
parametro.document.getElementById('2').value = "nit_proveedor" ;
//parametro.document.getElementById('3').value = "aseguradoranit" ;
 
}
</script>
<body>
<table width="45%" border="0" align="center" cellpadding="0" cellspacing="0">
  <tr>
    <td colspan="2"></td>
</tr>
  <tr>
    <td colspan="2" class="textcen">&nbsp;</td>
  </tr>
<tr>
    <td width="28" height="21"><center>
      <form name="form1" method="post" action="agregarr.php">
        <table width="874" border="0" align="center" cellpadding="0" cellspacing="0" class="hg">
          <tr>
            <td height="32" colspan="3" bgcolor="#FF6600"><span class="texy"><center>
              AGREGAR REPARACIÓN AL VEHICULO <? echo strtoupper($placa_reparaciones) ?>
            </center></span></td>
          </tr>
          <tr>
            <td>&nbsp;</td>
            <td height="32" colspan="2"><input name="id_reparaciones" type="hidden" id="id_reparaciones" size="40"></td>
          </tr>
          <tr>
            <td width="12">&nbsp;</td>
            <td width="137" height="32"><span class="texy">Placa:</span></td>
            <td width="725"><input name="placa_reparaciones" type="text" id="placa_reparaciones" value="<?php echo $placa_reparaciones ?>" size="12" readonly></td>
          </tr>
          <tr>
            <td>&nbsp;</td>
            <td height="31"><span class="texy">Fecha Ingreso:</span></td>
            <td><input name="fechaentrada_reparaciones" type="date" id="fechaentrada_reparaciones" value="<?php echo $fechaentrada_reparaciones ?>" size="40" required>
              &nbsp;Hora Entrad:
<input name="hora1" type="text"  class="hora1" id="hora1" value="00:00" size="5" /></td>
          </tr>
          <tr>
            <td>&nbsp;</td>
            <td height="32"><span class="texy">Fecha Salida:</span></td>
            <td><input name="fechasalida_reparaciones" type="date" id="fechasalida_reparaciones" value="<?php echo $fechasalida_reparaciones ?>" size="40">              &nbsp;Hora Salida:
<input name="hora2" type="text"  class="hora2" id="hora2" value="00:00" size="5" /></td>
          <script>
	document.querySelector('.hora1').addEventListener('keypress',validateHour);
	document.querySelector('.hora1').addEventListener('blur',formatHour);
	document.querySelector('.hora2').addEventListener('keypress',validateHour);
	document.querySelector('.hora2').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);
			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 para add campos--------------->
<script type="text/javascript">
$(document).ready(function(){
    var maxField = 20; //Input fields increment limitation
    var addButton = $('.add_button'); //Add button selector
    var wrapper = $('.field_wrapper'); //Input field wrapper
    var fieldHTML = '<div><table width="459" border="0" cellpadding="0" cellspacing="0"><tr><td width="32"><input name="cantidad_repuesto[]" type="text"  class="form-control-file multiplicando" id="cantidad_repuesto" size="2" onChange="multiplicar();"/></td><td width="123"><input name="repuesto_repuesto[]" type="text"  class="form-control-file" id="repuesto_repuesto" size="20" onkeyup="javascript:this.value=this.value.toUpperCase();"/></td><td width="89"><input name="proveedor_repuesto[]" type="text"  class="form-control-file" id="proveedor_repuesto" size="14" onClick="popupnit()" readonly/></td><td width="80"><input name="nitproveedor_repuesto[]" type="text"  class="form-control-file" id="nitproveedor_repuesto" size="12" readonly/></td><td width="75"><input name="valoruni_repuesto[]" type="text"  class="form-control-file multiplicador" id="valoruni_repuesto" size="8" onChange="multiplicar();"/></td><td width="60"><input name="valortotal_repuesto[]" type="text"  class="form-control-file resultado" id="valortotal_repuesto" size="8"/></td><a href="javascript:void(0);" style="color: blue; float:right;" class="remove_button" title="Remove field">X</a></table></div>'; //New input field html
    var x = 1; $(addButton).click(function(){
        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
    });
});
</script>
          </tr>
          <tr>
            <td>&nbsp;</td>
            <td height="32"><span class="texy">Tipo Reparación:</span></td>
            <td><select name="tipo_reparaciones" id="tipo_reparaciones">
              <option value="">Seleccione</option>
              <option value="Preventiva">Preventiva</option>
              <option value="Correctiva">Correctiva</option>
            </select></td>
          </tr>
          <tr>
            <td>&nbsp;</td>
            <td height="50" colspan="2"><table width="859" border="0" cellpadding="0" cellspacing="0">
              <tr>
                <td width="78">CANT</td>
                <td width="181">REPUESTO</td>
                <td width="152">PROVEEDOR</td>
                <td width="79">NIT</td>
                <td width="115">VALOR UNIT</td>
                <td width="254">TOTAL</td>
              </tr>
            </table>
              <div style="width:79%" class="field_wrapper">
 
                <div style="width:100%">
  <table width="448" border="0" cellpadding="0" cellspacing="0">
    <tr>
      <td width="123"><input name="cantidad_repuesto[]" type="text"  class="form-control-file multiplicando" id="cantidad_repuesto" size="2" onChange="multiplicar();"/></td>
      <td width="32"><input name="repuesto_repuesto[]" type="text"  class="form-control-file" id="repuesto_repuesto" size="20" onkeyup="javascript:this.value=this.value.toUpperCase();"/></td>
      <td width="89"><input name="proveedor_repuesto[]" type="text"  class="form-control-file" id="proveedor_repuesto" onClick="popupnit()" size="14" readonly/></td>
      <td width="80"><input name="nitproveedor_repuesto[]" type="text"  class="form-control-file" id="nitproveedor_repuesto" size="12" readonly/></td>
      <td width="75"><input name="valoruni_repuesto[]" type="text"  class="form-control-file multiplicador" id="valoruni_repuesto" size="8" onChange="multiplicar();"/></td>
      <td width="49"><input name="valortotal_repuesto[]" type="text"  class="form-control-file resultado" id="valortotal_repuesto" size="8"/>
     </td>
      </tr>
  </table>
                </div>
              </div>
            <a href="javascript:void(0);" style='color:blue' class="add_button"><span class="kk">+ Repuesto</span></a></td>
          </tr>
          <tr>
            <td>&nbsp;</td>
            <td height="32"><span class="texy">Conductor</span></td>
            <td><select style="width:250px" name="conductor_reparaciones" required="required" class="campos selector" id="conductor_reparaciones">
              <option value="">Seleccione:</option>
              <?php $query = $mysqli -> query ("SELECT * FROM conductores_nom WHERE estado_conductor='activo' AND pqr_conductor='1' ORDER BY nombre_conductor ASC");
          while ($valores = mysqli_fetch_array($query)) {echo '<option value="'.strtoupper ($valores[nombre_conductor]).'">'.strtoupper ($valores[nombre_conductor]).'</option>';
          }
		  ?>
            </select></td>
          </tr>
          <tr>
            <td>&nbsp;</td>
            <td height="32"><span class="texy">Estado Reparación:</span></td>
            <td><select  style="width:200px" name="estado_reparaciones" id="estado_reparaciones" class="campos selector" required>
                <option value="Vigente" selected>Vigente</option>
                <option value="Listo">Listo</option>
            </select></td>
          </tr>
          <tr>
            <td>&nbsp;</td>
            <td height="32" colspan="2"><input type="submit" name="button" id="button" value="Aceptar">
              <input type="submit" name="button2" id="button2" onClick="window.close();" value="Cancelar" />
              &nbsp;</td>
          </tr>
          <tr>
            <td colspan="3">&nbsp;</td>
          </tr>
          <tr>
            <td height="30" colspan="3" bgcolor="#FF6600">&nbsp;</td>
          </tr>
        </table>
      </form>
    </center></td>
    <td width="550">&nbsp;</td>
</tr>
  <tr>
    <td height="21" colspan="2"><p>&nbsp;</p>
</body>
</html>
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 algoritmo
Val: 37
Ha aumentado su posición en 2 puestos en JavaScript (en relación al último mes)
Gráfica de JavaScript

funcion no funciona dentro de field_wrapper

Publicado por algoritmo (14 intervenciones) el 19/09/2022 22:52:53
Hola

Lamento no disponer de más tiempo para explicar con más detalle tus muchos problemas.

Te indico lo que veo, sobre la marcha:

- Necesitar identificar de forma clara a los objetos que intervienen en la operación. Estás utilizando document.getElementsByClassName, y ésto te ofrece una lista con TODOS los objetos de esa clase. Para obtener el resultado necesitas saber el orden del objeto dentro de la lista. En principio sería: document.getElementsByClassName('multiplicando')[0].value

- Aunque corrijas lo anterior, cuando creas nuevas filas incorporas nuevos objetos que SON IDÉNTICOS A OTROS QUE YA EXISTEN, por lo que no hay manera de identificar con rigor el objeto que hay que tratar.

- Conclusión: Debes modificar sustancialmente tu código para conseguir que cada nueva fila incorpore objetos que de alguna manera sean identificados de forma única.

- Se me ocurre que la variable 'fieldHTML' no sea siempre la misma, y se vean afectados los 'id' de los objetos dependiendo de un contador que va a controlar el número de fila.............................

- No lo veo fácil para alguien no experimentado. Pero ánimo

Un saludo
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