JavaScript - Estoy muy perdida.... AYUDA

 
Vista:
sin imagen de perfil

Estoy muy perdida.... AYUDA

Publicado por anonymous (2 intervenciones) el 30/10/2019 01:26:17
Buenas noches,

Necesito hacer este ejercicio, y no se como hacerlo. Os dejo el enunciado y lo que he hecho hasta el momento...

Pero.... me esta costando la vida.

Si alguien caritativo me puede echar una mano, os lo agradeceria muchisimo

El enunciado es:

Se propone realizar una página web que calcule la letra del número de DNI introducido
por el usuario

De acuerdo con la web del Ministerio del Interior el algoritmo para calcular el DNI es el siguiente; se divide el
número entre 23 y el resto se sustituye por una letra que se determina por inspección mediante la siguiente
tabla:

Por ejemplo, si el número del DNI es 12345678 al dividirlo entre 23 da un resto de 14, luego la letra sería la Z: el resultado sería 12345678Z.

El programa ha de cumplir los siguientes requisitos:

- Se ha de solicitar un número y una letra de DNI al usuario.
- Se deben validar las entradas del usuario. En el caso de no sea correcta se deberán indicar los motivos del error.
- No se debe permitir una entrada vacía ni una entrada no numérica en el caso del número de DNI, ni una entrada numérica y superior a un carácter en el caso de la letra.
- Se ha de permitir el uso de letras mayúsculas y minúsculas.
- Los mensajes de validación se mostrarán mediante ventanas emergentes.
- Si se produce un error se borrará la entrada del usuario para que vuelva a introducir de nuevo los datos.
- Se usará un array para almacenar las diferentes letras.
- Se mostrará en la propia página la letra resultado (utilizando funciones del DOM) usando un tipo de letra grande, mínimo "h1".
- Si la letra introducida por el usuario no coincide con la calculada se mostrará en la propia página con un formato "h3" en rojo y el mensaje en verde en caso contrario.
- Para el cálculo de la letra del DNI podrá utilizarse un botón para tal fin o bien pulsar la tecla "Enter" una vez tecleada la entrada del usuario. La pulsación de "Enter" se ha de detectar tanto en el campo de entrada para el número como en el campo de entrada para la letra.
---------------------------------------------------------------------------------------------------------

Aqui esta el código que yo he hecho.... pero me falta mucho y no se por donde seguir.



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
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="widht=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie-edge">
    <title> Calculo DNI</title>
</head>
<header class="entry-header">
    <h1 class="entry-title"> Por favor, Introduce tu número de DNI y la letra</h1>
</header>
<body>
 
<script type="text/javascript">
 
    function calcula() {
        if (document.f.dni.value=='') { alert('OJO: Introduce los números ANTES de pulsar el botón'); }
        else {
                var prime = document.f.dni.value.trim().charAt(0).toUpperCase();
                if ( prime == 'X' || prime == 'Y' || prime == 'Z' ) {
                  document.f.dni.value=document.f.dni.value.replace(/\D/g, "");
                  var num=parseInt(document.f.dni.value);
                  var letras='TRWAGMYFPDXBNJZSQVHLCKET';
                  var cifras=num.toString().length;
                  var ceros=Array(7-cifras+1).join('0');
                  num = num+(prime.charCodeAt(0)-88)*10000000;
                  var letra=letras.charAt(num%23);
                  num = num-(prime.charCodeAt(0)-88)*10000000;
                  var cifras=num.toString().length;
                  var ceros=Array(7-cifras+1).join('0');
                  if (isNaN(num)) { alert('NOTA: Introduce un número correcto'); }
                  else            { document.f.dni.value=prime+ceros+num+"-"+letra;
                                    document.getElementById("txt").style.width = "7.5rem";
                                    document.getElementById("txt").style.padding = "0.5em 0.5em 0.5em 0em";
                                    document.f.txt.value="NIE:"; NoN = "NIE"; }
 
                } else if ( prime == 'K' || prime == 'L' || prime == 'M' ) {
                  document.f.dni.value=document.f.dni.value.replace(/\D/g, "");
                  var num=parseInt(document.f.dni.value);
                  var letras='TRWAGMYFPDXBNJZSQVHLCKET';
                  var cifras=num.toString().length;
                  var ceros=Array(7-cifras+1).join('0');
                  var letra=letras.charAt(num%23);
                  if (isNaN(num)) { alert('NOTA: Introduce un número de DNI correcto'); }
                  else            { document.f.dni.value=prime+ceros+num+"-"+letra;
                                    document.getElementById("txt").style.width = "7.5rem";
                                    document.getElementById("txt").style.padding = "0.5em 0.5em 0.5em 0em";
                                    document.f.txt.value="NIF:"; NoN = "NIF"; }
                } else {
                  document.f.dni.value=document.f.dni.value.replace(/\D/g, "");
                  var num=parseInt(document.f.dni.value);
                  var letras='TRWAGMYFPDXBNJZSQVHLCKET';
                  var cifras=num.toString().length;
                  var ceros=Array(8-cifras+1).join('0');
                  var letra=letras.charAt(num%23);
                  if (isNaN(num)) { alert('NOTA: Introduce SOLO NUMEROS (ninguna letra) para calcular la letra del NIF'); }
                  else            { document.f.dni.value=ceros+num+"-"+letra;
                                    document.getElementById("txt").style.width = "7.5rem";
                                    document.getElementById("txt").style.padding = "0.5em 0.5em 0.5em 0em";
                                    document.f.txt.value="NIF:"; NoN = "NIF"; }
                }
</script>
<form id="f" name="f" method="POST" action="javascript:calcula()"; style="text-align:center;">
    <fieldset id="DNI" style="margin-top:1em;">
        <label for="dni">
            <<h1> Teclea los números del DNI y pulsa "Validar"></label>
<div style="clear:both;"></div>
<input id="txt" style="font-size: 2.5rem; width: 0%; padding: 0.5em 0em; margin: 0.5em 0em; text-align: right; background-color: white; border-width: 0px; "type="text" name="txt" value="" title=" DNI" readonly="">
<input style="font-size: 2.5rem; width: 60%;" type="text" name="dni" id="dni" value="" onclick="" onkeyup="salto(this, 12, 'submit')" title="Introduce DNI o NIE" accesskey="d" maxlength="12"> ;>
 
function onkeyup(event) {
  salto(this, 12, 'submit')
}
<input id="submit" name="submit" type="submit" value="Calcular Letra DNI" title="Calcular Letra DNI" accesskey="n">
<input id="limpiar" name="limpiar" type="reset" value="Borrar" title="Borrar Todo" accesskey="b" onclick="document.f.dni.focus(); document.getElementById('txt').style.width = '0%'; document.getElementById('txt').style.padding = '0.5em 0em';">
function onclick(event) {
  document.f.dni.focus();
  document.getElementById('txt').style.width = '0%';
  document.getElementById('txt').style.padding = '0.5em 0em';
}
 
</fieldset>
 
</form>
<script type="text/javascript">document.f.dni.value=getParameterByName('nif');
    if (document.f.dni.value=="") { document.f.dni.value=getParameterByName('num'); }
  document.f.dni.focus();
  document.getElementById('icon').src = '/wp-content/uploads/2019/04/icon.png';
  if (getParameterByName('ok')=="ok") { calcula(); }</script>
  </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

Estoy muy perdida.... AYUDA

Publicado por Alejandro (532 intervenciones) el 30/10/2019 17:07:57
  • Alejandro se encuentra ahora conectado en el
  • chat de PHP
Puedes empezar por indentar bien tu código.
Como consejo siempre que abras algo ciérralo inmediatamente
1
2
3
4
5
function foo(){
}
if(condicion){
}
<div></div>

ya después escribes su contenido
1
2
3
4
5
6
7
function foo(){
    // Hacer algo;
}
if(condicion){
    // Hacer algo;
}
<div>Algún texto</div>

Esto realiza los requerimientos según lo que entendí
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
<!DOCTYPE html>
<html lang="es">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="widht=device-width, initial-scale=1.0">
		<meta http-equiv="X-UA-Compatible" content="ie-edge">
		<title> Calculo DNI</title>
	</head>
	<body>
		<header class="entry-header">
			<h1 class="entry-title"> Por favor, Introduce tu número de DNI y la letra</h1>
		</header>
 
		<form id="f" name="f" method="POST" action="javascript:calcula()"; style="text-align:center;">
			<fieldset id="DNI" style="margin-top:1em;">
				<label for="dni"><h1>Teclea los números del DNI y pulsa "Validar"</label>
				<div style="clear:both;"></div>
				<table style="width:60%;margin:auto;" >
					<tr>
						<td style="width:80%">Numero</td>
						<td style="width:20%">Letra</td>
					</tr>
					<tr>
						<td>
							<input style="font-size: 2.5rem; width: 100%; text-align:center" type="text" name="dniNumero" id="dniNumero" title="Introduce DNI o NIE" accesskey="d" maxlength="12" autocomplete="off">
						</td>
						<td>
							<input type="text" id="dniLetra" name="dniLetra" style="font-size: 2.5rem; width: 100%; text-align:center" maxlength="1" autocomplete="off" />
						</td>
					</tr>
				</table>
				<br />
				<input id="submit" name="submit" type="submit" value="Calcular Letra DNI" title="Calcular Letra DNI" accesskey="n">
				<input id="limpiar" name="limpiar" type="reset" value="Borrar" title="Borrar Todo" accesskey="b" />
				<br />
				<input id="txt" style="font-size: 2.5rem; padding: 0.5em 0em; margin: 0.5em 0em; text-align: center; background-color: white; border-width: 0px; "type="text" name="txt" title=" DNI" readonly="">
			</fieldset>
		</form>
 
		<script type="text/javascript">
			document.getElementById('limpiar').addEventListener('click',function(){
				document.getElementById('f').reset();
				document.getElementById('txt').style.backgroundColor = 'white';
			});
 
			function calcula() {
				dniNumero = document.getElementById('dniNumero').value;
				dniLetra  = document.getElementById('dniLetra').value;
 
				if( dniNumero.length == 0 ){
					alert("El numero no puede estar vacio.");
				}else if( isNaN(dniNumero) ){
					alert("El numero no lleva caracteres de letra o simbolo.");
					document.getElementById('dniNumero').value="";
					document.getElementById('dniNumero').focus();
				}else if( dniLetra.length == 0 ){
					alert("La letra no puede estar vacia.");
				}else if( !isNaN(dniLetra) ){
					alert("La letra no puede ser un numero.");
					document.getElementById('dniLetra').value="";
					document.getElementById('dniLetra').focus();
				}else{
					resultado = document.getElementById('txt');
					var letras='TRWAGMYFPDXBNJZSQVHLCKET';
					var letraGenerada = letras[dniNumero%23];
 
					resultado.value = dniNumero + letraGenerada;
					if( dniLetra.toUpperCase() == letraGenerada ){
						resultado.style.backgroundColor="green";
					}else{
						resultado.style.backgroundColor="Red";
					}
				}
			}
			document.getElementById('dniNumero').focus();
		</script>
	</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
1
Comentar
sin imagen de perfil

Estoy muy perdida.... AYUDA

Publicado por anonymous (2 intervenciones) el 31/10/2019 00:42:33
Muchisimas Gracias Alejandro,

Me has hecho ver la luz.

Y entonces, donde encajaria el usar un array para almacenar las diferentes letras???

esto estaria correcto??

1
2
3
var letras='TRWAGMYFPDXBNJZSQVHLCKET';
					var letraGenerada = letras[dniNumero%23];
var ceros=Array(7-cifras+1).join('0');
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

Estoy muy perdida.... AYUDA

Publicado por Alejandro (532 intervenciones) el 31/10/2019 05:01:48
  • Alejandro se encuentra ahora conectado en el
  • chat de PHP
Para JavaScript un string se compone de un array de caracteres es por eso que puedes acceder al carácter con letras[n] donde n es el indice.
Puedes declararlo explícitamente pero es mas labor.
1
var letras=['T', 'R', 'W', etc...]';

no se que intentas con esta linea
1
var ceros=Array(7-cifras+1).join('0');
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
1
Comentar