Botones

El uso de botones es una tarea muy comun que se puede resolver con eventos de JavaScript. Practicamente se puede usar eventos en cualquier elemento HTML pero los mas usados son input y button.

1. Uso de botones

Los elementos mas usados son input type=button y button, aunque en realidad puedes usar cualquier elemento HTML.

Todos los elementos HTML, EXCEPTO: <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style> y <title>

<input type=button value="titulo de boton" evento="valor">
<button evento="valor">titulo boton</button>

Nota que el texto que aparecerá en el boton input esta dado por el parametro value, en cambio en el elemento button el texto se pone entre la apertura y cierre del boton.

Tambien es posible invocar a una función creada como Script, asi:

<Script>
   funcion(){
      ...;
   }
</Script>

<input type=button value="titulo del boton" evento="funcion();">
<Button evento="funcion();">titulo del boton</Button>

2. Eventos

Existen cinco (5) posibles eventos a usar, aunque de lejos en mas usado en onClick.

2.1. onClick

Ejecute un JavaScript cuando se hace clic en un elemento HTML.

<input type=button value="titulo de boton" onClick="valor">
<button onClick="valor">titulo boton</button>
<button onclick="getElementById('resp').innerHTML = Date()">Que hora es ?</button>
<p id=resp>...</p>

...

2.2. onBlur

<input type=button value="titulo de boton" onBlur="valor">
<button onBlur="valor">titulo boton</button>

2.3. onFocus

<input type=button value="titulo de boton" onFocus="valor">
<button onFocus="valor">titulo boton</button>

2.4. onMouseDown

<input type=button value="titulo de boton" onMouseDown="valor">
<button onMouseDown="valor">titulo boton</button>

2.5. onMouseUp

<input type=button value="titulo de boton" onMouseUp="valor">
<button onMouseUp="valor">titulo boton</button>

3. Métodos

MethodDescription
blurRemoves focus from the button.
clickSimulates a mouse-click on the button.
focusGives focus to the button.
handleEventInvokes the handler for the specified event.
In addition, this object inherits the watch and unwatch methods from Object

4. Ejemplos

The following example creates a button named calcButton. The text "Calculate" is displayed on the face of the button. When the button is clicked, the function calcFunction is called.

<INPUT TYPE="button" VALUE="Calculate" NAME="calcButton"
   onClick="calcFunction(this.form)">

blur

Removes focus from the button.

Examples

The following example removes focus from the button element userButton:

userButton.blur()

This example assumes that the button is defined as

<INPUT TYPE=button VALUE="Boton de usurio">

Simulates a mouse-click on the button, but does not trigger the button's onClick event handler.

2. Ejemplos

2.1 Ejemplo 1

En este ejemplo el formulario "myForm1" contiene un campo texto y un botón. Cuando haces clic sobre el botón se acciona el evento onClick que usa this.form.name para hacer referencia a "myForm1" y ponerlo como valor en el campo texto.

<form name=myForm1>
Campo texto: <input type=text name=texto>
<input type=button value='Muestra nombre del formulario' onClick='this.form.texto.value=this.form.name'>
</form>

Campo texto:

2.2 Ejemplo 2

El siguiente ejemplo se muestra un formulario con varios elementos. Cuando el usuario hace clic en el botón2, la función showElements muestra un cuadro de diálogo de alerta que contiene los nombres de cada elemento en el formulario "myForm2".

<script>
   function showElements(theForm) {
      str = "Elementos del formulario " + theForm.name + ":\n"
      for (i=0; i<theForm.length; i++){
         str += i + " " + theForm.elements[i].name + "\n"
      }
      alert(str)
   }
</script>
<form name=myForm2>
   Muestra aqui: <INPUT TYPE=text NAME=texto>
   <INPUT TYPE=button NAME=boton1 VALUE="Muestra nombre del formulario" onClick="this.form.texto.value=this.form.name">
   <INPUT TYPE=button NAME=boton2 VALUE="Muestra elementos del formulario" onClick="showElements(this.form)">
</form>

Muestra aqui:

2.3 Ejemplo 3

Para invocar una nueva pagina.

<button onClick="window.location.href='index.htm'">Titulo</button>

2.4 Ejemplo 4

Para cerrar la ventana actual puedes usar window.close().

<button onClick='window.close()'>Titulo</button>

If multiple objects on the same form have the same NAME attribute, an array of the given name is created automatically. Each element in the array represents an individual Form object. Elements are indexed in source order starting at 0. For example, if two Text elements and a Button element on the same form have their NAME attribute set to "myField", an array with the elements myField[0], myField[1], and myField[2] is created. You need to be aware of this situation in your code and know whether myField refers to a single element or to an array of elements.

Examples

In the following example, the valueGetter function uses a for loop to iterate over the array of elements on the valueTest form. The msgWindow window displays the names of all the elements on the form:

function valueGetter() {
   var msgWindow=window.open("")
   for (var i=0; i")
   }
}

In the following example, the first statement creates a window called netscapeWin. The second statement displays the value "netscapeHomePage" in the Alert dialog box, because "netscapeHomePage" is the value of the windowName argument of netscapeWin.

Button.value

For all Button objects, the value of the type property is "button". This property specifies the form element's type.

Examples

The following example writes the value of the type property for every element on a form.

For (var i=0; itype is " + document.form1.elements[i].type)
}

value

A string that reflects the button's VALUE attribute.

This string is displayed on the face of the button.

The value property is read-only for Macintosh and UNIX systems. On Windows, you can change this property.

When a VALUE attribute is not specified in HTML, the value property is an empty string.

Do not confuse the value property with the name property. The name property is not displayed on the screen; it is used to refer programmatically to the objects.

Ejemplos

The following function evaluates the value property of a group of buttons and displays it in the msgWindow window:

function valueGetter() {
   var msgWindow=window.open("")
   msgWindow.document.write("submitButton.value is " +
   document.valueTest.submitButton.value + "
") msgWindow.document.write("resetButton.value is " + document.valueTest.resetButton.value + "
") msgWindow.document.write("helpButton.value is " + document.valueTest.helpButton.value + "
") msgWindow.document.close()}

The previous example assumes the buttons have been defined as follows:

<INPUT TYPE=submit NAME=Enviar>
<INPUT TYPE=reset NAME=Resetear>
<INPUT TYPE=button NAME=Ayuda VALUE=Ayuda>