martes, 12 de febrero de 2013

Leer el valor de un campo de texto con jQuery

Otra forma que tiene el jQuery para interactura con HTML es que podemos leer y escribir en las cajas de texto de los formularios. Esto lo realizamos por medio de método val().

Por ejemplo, leemos el valor de una caja de texto y escribimos su valor en la parte inferior:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Val</title>
<style>
    p { color:blue; margin:8px; }
</style>
<script src="jquery.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(inicio);
function inicio(){
    $("input").keyup(function () {
        var v = $(this).val();
        v = v.toUpperCase()
        $("p").text(v);
        }).keyup();
    }
</script>
</head>
<body>
<input type="text" value="Hola"/>
<p></p>
</body>
</html>


Ejemplo: http://pacoarce.com/jQuery/Val.html
Curso completo: https://www.udemy.com/jquery-y-mobile/

Modificar los atributos desde jQuery

Desde jQuery, podemos modificar a nuestro gusto cualquier valor de cualquier etiqueta de un documento DOM en tiempo de ejecución. Primero debemos identificar el objeto, ya sea por medio de un identificador, etiqueta o clase, y luego utilizar el método attr(). 

Si el selector regresa más de un elemento, sólo se modificará el primero.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Atributos</title>
<script src="jquery.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(inicio);
function inicio(){
    $("#chica").click(onChica);
    $("#mediana").click(onMediana);
    $("#grande").click(onGrande);
    $("#titulo").click(onTitulo);
}
function onChica(){
    $("img").attr({width:"160px", height:"196px"});
}
function onMediana(){
    $("img").attr({width:"320px", height:"392px"});
}
function onGrande(){
    $("img").attr({width:"480px", height:"588px"});
}
function onTitulo(){
    var titulo = $("img").attr("title");
    $("#texto").text(titulo);
   
}
</script>
</head>

<body>
<input id="chica" type="button" value="Chica">
<input id="mediana" type="button" value="Mediana">
<input id="grande" type="button" value="Grande">
<input id="titulo" type="button" value="Titulo">
<br>
<img src="imagenes/afrodita160x196.jpg" width="160" height="196" alt="Afrodita" title="El nacimiento de Venus, William-Adolphe Bouguereau, 1879">
<p id="texto"></p>
</body>
</html>


Ejemplo: http://pacoarce.com/jQuery/Atributos.html 
Curso completo: https://www.udemy.com/jquery-y-mobile/

lunes, 11 de febrero de 2013

Leer y escribir el código HTML desde jQuery

Aunque ya tenemos en JavaScript una función similar (innerHTML) en jQuery tenemos el método html() que nos permite leer y escribir el código html de un objeto dentro del DOM.

Este método no funciona para documentos XML.

Si el selector regresa más de un elemento, sólo el primer elemento regresa su código HTML.

Esta función puede presentar algunos problemas con el navegador Internet Explorer, en versiones antigüas, ya que se basa en el comando innerHTML de JavaScript:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>HTML</title>
<script src="jquery.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(inicio);
function inicio(){
    $("p").click(onCambia);   
}
function onCambia(){
    var tt = $(this).html();
    $(this).text(tt);   
}
</script>
</head>

<body>
<p><strong>Este</strong> es <em>un párrafo</em></p>
<p>Este <input type="button" value="botoncito"/> no es otra cosa que código HTML</p>
<p>Esta imagen <img src="imagenes/animales/medusa.png"/> también es código HTML</p>
</body>
</html>

Ejemplo: http://pacoarce.com/jQuery/html.html
Manipulación del DOM con jQuery

Una parte muy importante de jQuery, es la posibilidad de manipular el DOM.

jQuery viene con un montón de métodos DOM relacionados, lo que hace que sea fácil de acceder y manipular los elementos y atributos en cualquier página web.


Leer el contenido - text (), html () y val()

Tres simples, pero útiles, métodos jQuery para la manipulación de DOM son:

     text () - Establece o devuelve el contenido de texto de los elementos seleccionados
     html () - Establece o devuelve el contenido de los elementos seleccionados (incluyendo el formato HTML)
     val () - Establece o devuelve el valor de los campos del formulario


<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>DOM</title>
<script src="jquery.js" type="text/javascript" language="javascript"></script>
<script type="text/javascript">
$(document).ready(inicio);
function inicio(){
    $("#pregunta").click(onPregunta);
    $("#respuesta").click(onRespuesta);
    $("#ventana").click(onVentana);
}
function onPregunta(){
    $("#texto").text("¿Quién pinto el Nacimiento de Venus?");   
}
function onRespuesta(){
    $("#texto").text("Sandro Bottichelli (1445 - 1510) en 1484");   
}
function onVentana(){
    var t = $("#texto").text();
    alert("El contenido del enunciado es: "+t);
}
</script>
</head>

<body>
<p id="texto">¿Quién pinto el Nacimiento de Venus?</p>
<input type="button" value="Pregunta" id="pregunta"/>
<input type="button" value="Respuesta" id="respuesta"/>
<input type="button" value="Ventana" id="ventana"/>
</body>
</html>

 

 Ejemplo: http://pacoarce.com/jQuery/DOM.html

Curso completo en: http://www.udemy.com/jquery-y-mobile/ 

Las funciones de callback en jQuery

Las sentencias de JavaScript se ejecuta línea por línea. Sin embargo, con los efectos, la siguiente línea de código puede ejecutarse aunque el efecto no está terminado. Esto puede crear errores.

Para evitar esto, se puede crear una función de callback. Una función de callback se ejecuta después de que el efecto actual terminó.

Sintaxis: $ (selector).hide(velocidad, callback).




Curso completo de jQuery en: http://www.udemy.com/jquery-y-mobile

Encadenamiento de métodos con jQuery:

 Por lo general escribimos las sentencias jQuery una a la vez (una después de la otra).

Sin embargo, existe una técnica llamada encadenamiento, que nos permite ejecutar varios comandos con jQuery, uno tras otro, en el mismo elemento o elementos.

Sugerencia: De esta manera, los navegadores no tienen que encontrar el mismo elemento  más de una vez.

Para encadenar una acción, sólo tiene que añadir la acción a la acción anterior y unirlas por medio de un punto.


Cuando encadenamos métodos en jQuery, la línea de código puede ser bastante larga. Sin embargo, jQuery no es muy estricto acerca de la sintaxis: puede darle formato como usted desee, incluyendo saltos de línea y sangrías.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Afrodita Muestra/Oculta</title>
<style>
#afrodita{
    width:800px;
    height:502px;
    background-image:url(imagenes/afrodita.jpg);
    background-repeat:no-repeat;
    background-size:100%;
}
p{
    background-color:#CCC;
    text-align:center;
}
</style>
<script src="jquery.js" type="text/javascript" language="javascript"></script>
<script type="text/javascript">
$(document).ready(inicio);
function inicio(){
    $("#toggle").click(onSelecciona);
   
}
function onSelecciona(){
    $("p").css("color","red").slideUp(1000).slideDown(1000);
   
}
</script>
</head>

<body>
<div id="afrodita"><p>El nacimiento de Venus, por Sandro Botticelli (1445 - 1510)</p></div>
<input type="button" id="toggle" value="Selecciona"/>

</body>
</html> 


Curso completo de jQuery en:
http://www.udemy.com/jquery-y-mobile/

miércoles, 6 de febrero de 2013

Los ciclos en Objective-C

¿Por qué utilizar Loops?


Las sentencias de bucle son el principal mecanismo para contar un equipo que una secuencia de tareas necesita ser repetido un número específico de veces. 
Supongamos, por ejemplo, que usted tiene la obligación de agregar un número a sí mismo diez veces. 
Una forma de hacerlo podría ser la de escribir el siguiente código de Objective-C:


int j = 10;

j += j;
j += j;
j += j;
j += j;
j += j;
j += j;
j += j;
j += j;
j += j;
j += j;


Si bien esto es algo engorroso funciona.
¿Qué pasaría, sin embargo, si usted necesita para llevar a cabo esta tarea 100 o incluso 10.000 veces?
Escritura de Objective-C código para realizar esto como anteriormente sería prohibitivo.
Este escenario es exactamente lo que el bucle for tiene la intención de manejar.
La sintaxis de una Objective-C para el bucle es la siguiente:

for ( ''inicio''; ''expresión condicional''; ''incremento/decremento'' )
{
      // sentencias a ser ejecutadas
} 

El inicializador normalmente inicializa una variable de contador.
Tradicionalmente, el nombre de la variable i se utiliza para este propósito, aunque cualquier nombre de variable es válido.
Por ejemplo:
Esto pone el contador a la variable i y lo establece en cero. 
Tenga en cuenta que la anteriormente utilizada Objective-C estándar (c89) requiere que esta variable sea declarado con anterioridad a su uso en el bucle. 
Por ejemplo:

int i=0;

for (i = 0; i < 100; i++)
{
     // Statements here
}

El estándar actual (c99) permite la variable que se declara y se inicializa en el bucle de la siguiente manera:

for (int i=0; i<100; i++)
{
    //sentencias
}


Si compila código que contiene esta construcción usando el compilador C89 un nivel que puede obtener un error similar al siguiente:

error: "para" bucle declaración inicial utilizarse fuera de modo C99

Si usted ve este mensaje, debería ser capaz de cambiar al modo de C99 mediante la adición del std = c99-de línea de comandos bandera a su comando de compilación.
Por ejemplo:

clang-std = c99-marco de la Fundación hello.m-o hola

La expresión condicional especifica la prueba para llevar a cabo para verificar si el bucle se ha realizado el número requerido de iteraciones. Por ejemplo, si queremos bucle 10 veces:

i <10;

Por último, la expresión bucle especifica la acción a realizar en la variable contador. Por ejemplo, para incrementar en 1:

i + +;

El cuerpo de instrucciones que se ejecutan en cada iteración del bucle está contenido dentro del bloque de código definida por la abertura ({) y de cierre (}) llaves.
Si sólo hay una declaración se va a ejecutar las llaves son opcionales, aunque todavía se recomienda para mejorar la legibilidad del código y para que no se olvide de la añadirlos si posteriormente aumentar el número de sentencias que se realizan en el bucle.

Llevando todo esto juntos podemos crear un bucle para realizar la tarea se indica en el ejemplo anterior:

int j = 10;

for (int i=0; i<10; i++)
{
      j += j;
}

NSLog (@"j = %i", j);

Alcance de las variables dentro de un ciclo

Un punto clave a observar en la creación de bucles es que las variables definidas en el cuerpo de un bucle sólo son visibles para el código dentro del bucle.
Este es el concepto conocido como ámbito de aplicación.
Si, por ejemplo, un myCounter variable se define en un bucle, la variable deja de existir una vez que el bucle termina:

// variable myCounter does not yet exist

for (int i = 0; i < 10; i++)
{
       int myCounter = 0; //myCounter variable created in scope of for loop

       myCounter += i;
}

// after loop exit variable myCounter is now out of scope and ceases to exist

Creating an Infinite for Loop

A for loop that will execute an infinite number of times may be constructed using for (;;) syntax. For example, the following code sample will output Hello from Objective-C until the program is manually terminated by the user (or the computer is turned off or rebooted):
for (;;)
{
    NSLog (@"Hello from Objective-C");
}

Breaking Out of a for Loop

Having created a loop it is possible that under certain conditions you might want to break out of the loop before the completion criteria have been met (particularly if you have created an infinite loop). One such example might involve continually checking for activity on a network socket. Once activity has been detected it will be necessary to break out of the monitoring loop and perform some other task.
For the purpose of breaking out of a loop, Objective-C provides the break statement which breaks out of the current loop and resumes execution at the code directly after the loop. For example:
int j = 10;

for (int i = 0; i < 100; i++)
{
     j += j;

     if (j > 100)
          break;

     NSLog (@"j = %i", j);
}
In the above example the loop will continue to execute until the value of j exceeds 100 at which point the loop will exit.

Nested for Loops

So far we have looked at only a single level of for loop. It is also possible to nest for loops where one for loop resides inside another for loop. For example:
int j;

for (int i = 0; i < 100; i++)
{
     NSLog( @"i = %i", i);

     for (j = 0; j < 10; j++)
     {
             NSLog ( @"j = %i", j);
     }
}
The above example will loop 100 times displaying the value of i on each iteration. In addition, for each of those iterations it will loop 10 times displaying the value of j.

Breaking from Nested Loops

An important point to be aware of when breaking out of a nested for loop is that the break only exits from the current level of loop. For example, the following Objective-C code example will exit from the current iteration of the nested loop when j is equal to 5. The outer loop will, however, continue to iterate and, in turn execute the nested loop:
for (int i = 0; i < 100; i++)
{
     NSLog( @"i = %i", i);

     for (int j = 0; j < 10; j++)
     {
             if (j == 5)
                   break;

             NSLog ( @"j = %i", j);
     }
}

Continuing for Loops

Another useful statement for use in loops in the continue statement. When the execution process finds a continue statement in any kind of loop it skips all remaining code in the body of the loop and begins execution once again from the top of the loop. Using this technique we can construct a for loop which outputs only even numbers between 1 and 9:
for (int i = 1; i < 10; i++)
{
          if ((i % 2) != 0)
               continue;

          NSLog( @"i = %i", i);
}
In the example, if i is not divisible by 2 with 0 remaining the code performs a continue sending execution to the top of the for loop, thereby bypassing the code to output the value of i. This will result in the following output:
2
4
6
8

Using for Loops with Multiple Variables

In the examples we have covered so far we have used a single variable within the for loop construct. Objective-C actually permits multiple variables to be modified within the looping process. In the following example, the for loop increments two variables, i and j:
int j;
int i;

for (j = 0, i = 0; i < 10; i++, j++)
{
          NSLog( @"i = %i, j = %i", i, j);
}
Note that although both i and j are initialized and incremented in this loop, the number of times the loop is to be performed is still based on the value of i through the i > 10 expression. The initialization and modification expressions for additional variables do not need to be the same as the control variable. For example, the following example initializes j to 5 and multiplies it by 2:
int j;
int i;

for (j = 1, i = 0; i < 10; i++, j *= 2)
{
          NSLog( @"i = %i, j = %i", i, j);
}
When the above loop is executed we get output similar to:
2009-10-13 09:32:22.498 t[1867:10b] i = 0, j = 1
2009-10-13 09:32:22.500 t[1867:10b] i = 1, j = 2
2009-10-13 09:32:22.500 t[1867:10b] i = 2, j = 4
2009-10-13 09:32:22.501 t[1867:10b] i = 3, j = 8
2009-10-13 09:32:22.501 t[1867:10b] i = 4, j = 16
2009-10-13 09:32:22.502 t[1867:10b] i = 5, j = 32
2009-10-13 09:32:22.502 t[1867:10b] i = 6, j = 64
2009-10-13 09:32:22.503 t[1867:10b] i = 7, j = 128
2009-10-13 09:32:22.503 t[1867:10b] i = 8, j = 256
2009-10-13 09:32:22.503 t[1867:10b] i = 9, j = 512