Sesion1 LPII JavaScript
Sesion1 LPII JavaScript
LENGUAJE DE PROGRAMACION II
Ejercicios
1. En nuestro primer programa JavaScript podemos desplegar un simple mensaje de “Hola mundo”, para
hacerlo puedes usar el siguiente código:
<html>
<head>
<title>Primer programa en JavaScript</title>
<script>
alert("Hola mundo");
</script>
</head>
<body></body>
</html>
window.alert("Texto a mostrar");
alert("Texto a mostrar");
También con la función write() imprime el texto especificado en la página. Para imprimir texto
literalmente, escribe el texto en comillas simples y entre paréntesis:
<html>
<head>
<title>Javascript Ejem 1</title>
</head>
<body>
<script>
document. write("Hola mundo");
</script>
</body>
</html>
2. Función saludo con dos parámetros nombre y color, la misma que es incorporado en el cuerpo de la
página.
<!DOCTYPE html>
<html>
<head>
<title>Ej1-funcion write</title>
<script >
//función con dos parámetros nombre y color
function saludo (nombre, color) {
//imprimir nombre con estilo de color al texto
document.write("<h1 style=color:"+color+">"+nombre+"<h1>");
}
</script>
</head>
<body>
<script >
//inicialización de variables
var nom="Adrian";
var c="red";
//llamar o invocar a la función saludo
saludo(nom,c);
</script>
</body>
</html>
3. Función eval recoge una cadena que convierte en un código válido que después ejecuta.
<!DOCTYPE html>
<html>
<head>
<title>Ej1-funcion eval</title>
<script >
function evaluar(){
//la función eval recoge una cadena que convierte
//en un código válido que después ejecuta
frmx.resultado.value=eval(frmx.exp.value);
}
</script>
</head>
<body>
<form name="frmx">
Ingrese expresion matematica<input type=" type" name="exp"><br>
El resultado<input type=" type" name="resultado"><br>
<!--invoca a la función evaluar en el evento clic del boton-->
<input type="button" value="Evaluar" onclick="evaluar()">
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Ej1-white</title>
</head>
<body>
<table border="1">
<script >
var num,sum=0;
while(1){
num=parseInt(prompt("Ingrese nota:"));
if(isNaN(num)){
alert("Debe ingresar un valor numerico");
}else{
if(num==-1){
document.write("<tr><td>Total:"+sum+"</td> </tr>");
break;
}else{
document.write("<tr><td>"+ num+"</td> </tr>");
sum=sum + num;
}
}
}
</script>
</table>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Ej1-for</title>
</head>
<body>
<table border="1">
<script >
var f=prompt("Ingrese número de filas:");
var c=prompt("Ingrese color:");
for(var i=0;i<f;i++){
document.write("<tr><td style=background:"+ c
+">"+(i+1)+"</td><td>"+(i+1)*10+"</td></tr>");
}
</script>
</table>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Ej1-funcion isNaN</title>
<script >
function comprobar(){
var numero=parseFloat(frmx.numero.value);
alert(numero);
//evalua si es un numero
//isNaN intenta convertir el parámetro pasado a un número.
// Si el parámetro no se puede convertir, devuelve true; en caso
//contrario, devuelve false.
if (isNaN(numero)){
alert("Debe ingresar un valor numérico");
//limpia el input
frmx.numero.value="";
//ubica el cursor en el input
frmx.numero.focus();
}else{
alert("Correcto");
}
}
</script>
</head>
<body>
<form name="frmx">
Ingrese número <input type="text" name="numero"><br>
<input type="button" value="Comprobar" onclick="comprobar()">
</form>
</body>
</html>
7. Si queremos que después de un tiempo determinado se haga el llamado de una función, entonces lo
que debemos usar es el método "setTimeout". El método setTimeout utiliza 2 argumentos como
vemos a continuación.
setTimeout( Funcion , Tiempo ); el tiempo está en milisegundos
<!DOCTYPE html>
<html>
<head>
<title>Ej1-setTimeout</title>
</head>
<body>
<script>
function mensaje(){
setTimeout(myfuncion,3000);
}
function myfuncion(){
alert("JavaScript");
}
</script>
<button onclick="mensaje()">Ver Mensaje</button>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Ej2-setTimeout</title>
<script>
function mensaje(){
setTimeout(myfuncion,3000);
}
function myfuncion(){
alert("JavaScript");
}
</script>
</head>
<body onload="mensaje()">
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Ej3-setTimeout</title>
<script>
var num=0;
function mensaje(){
if(num<3){
setTimeout(alumno,3000);
num++;
}
}
function alumno(){
var nombre=prompt("Ingrese nombre y apellidos:");
alert(nombre+" veces: "+ num);
}
</script>
</head>
<body onload="mensaje()">
</body>
</html>
10. Hacer un Reloj, utilizando una función que usa el setTimeout para llamar a la misma función.
<!DOCTYPE html>
<html>
<head>
<title>Ej4-setTimeout</title>
<script>
function ActivarReloj(){
//Obteniendo datos del tiempo
var laHora = new Date();
var horario = laHora.getHours();
var minutero = laHora.getMinutes();
var segundero = laHora.getSeconds();
if(minutero<10)
minutero = "0" + minutero;
if(segundero<10)
segundero = "0" + segundero;
function DetenerReloj(){
// Deteniendo el setTimeout
clearTimeout(ahoraSonLas);
// Volviendo el boton 'Activar Reloj' a la normalidad
document.getElementById('botonActivar').disabled=false;
}
</script>
</head>
<body >
Parámetros
<!DOCTYPE html>
<html>
<head>
<script>
var x;
function abrirVentana()
{ opciones="toolbar=1, status=0, width=300, height=200";
x=window.open("ej2-formulario.html","",opciones);
}
function cerrarVentana()
{ x.close();
}
</script>
<!DOCTYPE html>
<html>
<head>
<script>
function abrirVentana()
{
// definimos la anchura y altura de la ventana
var altura=380;
var anchura=630;
}
function cerrarVentana()
{ x.close();
}
</script>
<title> Ej2-window.open </title>
</head>
Continuo código anterior:
<body>
<form name="frm1">
<input type="button" value="Abre Ventana"
onClick="abrirVentana();"><p>
<input type="button" value="Cierra Ventana"
onClick="cerrarVentana();">
</form>
</body>
</html>
</html>
13. Diseñe la página para seleccionar los cursos en las casillas de verificación, las mismas que
serán listadas en un área de texto:
14. Generar un arreglo con los valores seleccionados de las casillas de verificación, valores que
se imprimirán en el área de texto al presionar el botón procesar.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Formulario</title>
</head>
<body>
</body>
</html>
<html>
<head>
<title>HTML-JavaScript</title>
<script>
function validar() {
var n = document.f1.nom.value;
var c = document.f1.clave.value;
if (n == "") {
alert('Ingrese nombre');
return false;
} else if (c == "") {
alert('Ingrese clave');
return false;
}
return true;
}
</script>
</head>
<body>
<form name="f1" action="" method="post" onSubmit="return validar();">
Nombre: <input type="text" name="nom">
Clave: <input type="password" name="clave"> <br/>
<input type="submit" value="Enviar">
</form>
</body>
</html>
16. Modifiquemos la función validar (), asumiendo que el usuario es “monica” y clave “123”, ahora la
aplicación además de exigir ingresar nombre y clave deben ser “monica” y “123” respectivamente:
<html>
<head>
<title>Validacion</title>
<script>
function validar() {
var n = document.f1.nom.value;
var c = document.f1.clave.value;
if (n == "") {
alert('Ingrese nombre');
return false;
} else if (c == "") {
alert('Ingrese clave');
return false;
}else if(n!="monica"){
alert('Nombre incorrecto...');
return false;
}
else if(c!="123"){
alert('clave incorrecta...');
return false;
}
return true;
}
</script>
</head>
<body>
<form name="f1" action="" method="post" onSubmit="return validar();">
Nombre: <input type="text" name="nom">
Clave: <input type="password" name="clave"> <br/>
<input type="submit" value="Enviar">
</form>
</body>
</html>
La principal utilidad de JavaScript en el manejo de los formularios es la validación de los datos introducidos
por los usuarios. Antes de enviar un formulario al servidor, se recomienda validar mediante JavaScript los
datos insertados por el usuario. De esta forma, si el usuario ha cometido algún error al rellenar el
formulario, se le puede notificar de forma instantánea, sin necesidad de esperar la respuesta del servidor.
Aunque existen tantas posibles comprobaciones como elementos de formulario diferentes, algunas
comprobaciones son muy habituales: que se rellene un campo obligatorio, que se seleccione el valor de
una lista desplegable, que la dirección de email indicada sea correcta, que la fecha introducida sea lógica,
que se haya introducido un número donde así se requiere, etc.
function validar() {
<html>
<head>
<title>HTML-JavaScript</title>
<script>
if (n== "") {
alert('Ingrese nombre');
return false;
} else if (s == "") {
alert('Seleccione:\nTu sistema favorito');
return false;
}
else if (!getValueChekActivado()) {
alert("Elige tu deporte favorito para que el
formulario pueda ser enviado "+d);
return false;
}
else if (!getValueRadioActivado()) {
alert("Elige una opción de sexo para que el
formulario pueda ser enviado");
return false;
}
return true;
}
</script>
</head>
<body>
<form name="f1" action="" method="post" onSubmit="return validar();">
<table>
<tr>
<td>Tu Nombre</td>
<td><input type="text" name="nom"> </td>
</tr>
<tr>
<td>Tu sistema favorito</td>
<td>
<select name="sis">
<option value="-1"> Seleccione</option>
<option value="1"> Linux</option>
<option value="2"> Windows</option>
<option value="3">Mac</option>
</select>
</td>
</tr>
<tr>
<td>Tu deporte favorito</td>
<td>
<input type="checkbox" name="chkdep" value="Futbol"> Futbol
<input type="checkbox" name="chkdep" value="Futbol"> Voley
<input type="checkbox" name="chkdep" value="Ciclismo"> Ciclismo
<input type="checkbox" name="chkdep" value="Karate"> Karate
</td>
</tr>
<tr>
<td>Cual es tu Sexo ?</td>
<td>
<table>
<tr>
<td><input type="radio" name="rdsexo"> Hombre</td>
</tr>
<tr>
<td><input type="radio" name="rdsexo"> Mujer</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>Aficiones</td>
<td>
<textarea name="txta"> </textarea>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Enviar Datos">
<input type="submit" value="Restablecer">
</td>
<td>
</td>
</tr>
</table>
</form>
</body>
</html>
//*****ejecución de la aplicación ****