<input type="button">

Elementos <input> do tipo button são renderizados como um simples botão, que podem ser programados para controlar funcionalidades customizadas em qualquer lugar de uma página web quando for atribuído um evento (tipicamente para um evento click (en-US)).

Experimente

Nota: Enquanto elementos <input> do tipo button ainda são perfeitamente válidos, os novos elementos <button> são agora os favoráveis meios para criar botões. Uma etiqueta de texto (label) para um <button> pode ser inserida entre uma tag de abertura e outra de fechamento, podendo ser incluídas até imagens.

Value Um DOMString usado como uma etiqueta de botão.
Eventos click (en-US)
Atributos comuns suportados type, e value
atributos IDL value
Métodos Nenhum

Value

Seu atributo value de um elemento <input type="button"> contém uma DOMString que é usado como uma etiqueta (label) de um botão

html
<input type="button" value="Click Me" />

Se você não especificar um value, você obtém um botão vazio:

html
<input type="button" />

Usando buttons

Elementos <input type="button"> não possuem comportamento padrão (seu primos, <input type="submit"> e <input type="reset"> (en-US) são usados para submeter e resetar formulários). Para que botões possam fazer algo, você tem de escrever um código em JavaScript para fazê-lo trabalhar.

Um simples botão

Nós iremos começar criando um simples botão com um evento click (en-US) que inicia nossa máquina (bem, ele altera o value do botão e o contéudo texto do seguinte parágrafo):

html
<form>
  <input type="button" value="Start machine" />
</form>
<p>The machine is stopped.</p>
js
const button = document.querySelector("input");
const paragraph = document.querySelector("p");

button.addEventListener("click", updateButton);

function updateButton() {
  if (button.value === "Start machine") {
    button.value = "Stop machine";
    paragraph.textContent = "The machine has started!";
  } else {
    button.value = "Start machine";
    paragraph.textContent = "The machine is stopped.";
  }
}

O script recebe uma referência para o objeto HTMLInputElement representando o <input> no DOM, salvando esta referência na variável button. addEventListener() é então usado para criar uma função que será chamada quando o evento click (en-US) for executado no botão.

Adicionando atalhos de teclados aos botões

Keyboard shortcuts, also known as access keys and keyboard equivalents, let the user trigger a button using a key or combination of keys on the keyboard. To add a keyboard shortcut to a button — just as you would with any <input> for which it makes sense — you use the accesskey global attribute.

In this example, s is specified as the access key (you'll need to press s plus the particular modifier keys for your browser/OS combination; see accesskey for a useful list of those).

html
<form>
  <input type="button" value="Start machine" accesskey="s" />
</form>
<p>The machine is stopped.</p>

Note: The problem with the above example of course is that the user will not know what the access key is! In a real site, you'd have to provide this information in a way that doesn't intefere with the site design (for example by providing an easily accessible link that points to information on what the site accesskeys are).

Desativando e ativando um botão

To disable a button, simply specify the disabled global attribute on it, like so:

html
<input type="button" value="Disable me" disabled />

You can enable and disable buttons at run time by simply setting disabled to true or false. In this example our button starts off enabled, but if you press it, it is disabled using button.disabled = true. A setTimeout() (en-US) function is then used to reset the button back to its enabled state after two seconds.

If the disabled attribute isn't specified, the button inherits its disabled state from its parent element. This makes it possible to enable and disable groups of elements all at once by enclosing them in a container such as a <fieldset> element, and then setting disabled on the container.

The example below shows this in action. This is very similar to the previous example, except that the disabled attribute is set on the <fieldset> when the first button is pressed — this causes all three buttons to be disabled until the two second timeout has passed.

Note: Firefox will, unlike other browsers, by default, persist the dynamic disabled state of a <button> across page loads. Use the autocomplete attribute to control this feature.

Validação

Buttons não participam na validação; eles não tem um valor real para ser restringido.

Exemplos

The below example shows a very simple drawing app created using a <canvas> element and some simple CSS and JavaScript (we'll hide the CSS for brevity). The top two controls allow you to choose the color and size of the drawing pen. The button, when clicked, invokes a function that clears the canvas.

html
<div class="toolbar">
  <input type="color" aria-label="select pen color" />
  <input
    type="range"
    min="2"
    max="50"
    value="30"
    aria-label="select pen size" /><span class="output">30</span>
  <input type="button" value="Clear canvas" />
</div>

<canvas class="myCanvas">
  <p>Add suitable fallback here.</p>
</canvas>
js
var canvas = document.querySelector(".myCanvas");
var width = (canvas.width = window.innerWidth);
var height = (canvas.height = window.innerHeight - 85);
var ctx = canvas.getContext("2d");

ctx.fillStyle = "rgb(0,0,0)";
ctx.fillRect(0, 0, width, height);

var colorPicker = document.querySelector('input[type="color"]');
var sizePicker = document.querySelector('input[type="range"]');
var output = document.querySelector(".output");
var clearBtn = document.querySelector('input[type="button"]');

// covert degrees to radians
function degToRad(degrees) {
  return (degrees * Math.PI) / 180;
}

// update sizepicker output value

sizePicker.oninput = function () {
  output.textContent = sizePicker.value;
};

// store mouse pointer coordinates, and whether the button is pressed
var curX;
var curY;
var pressed = false;

// update mouse pointer coordinates
document.onmousemove = function (e) {
  curX = window.Event
    ? e.pageX
    : e.clientX +
      (document.documentElement.scrollLeft
        ? document.documentElement.scrollLeft
        : document.body.scrollLeft);
  curY = window.Event
    ? e.pageY
    : e.clientY +
      (document.documentElement.scrollTop
        ? document.documentElement.scrollTop
        : document.body.scrollTop);
};

canvas.onmousedown = function () {
  pressed = true;
};

canvas.onmouseup = function () {
  pressed = false;
};

clearBtn.onclick = function () {
  ctx.fillStyle = "rgb(0,0,0)";
  ctx.fillRect(0, 0, width, height);
};

function draw() {
  if (pressed) {
    ctx.fillStyle = colorPicker.value;
    ctx.beginPath();
    ctx.arc(
      curX,
      curY - 85,
      sizePicker.value,
      degToRad(0),
      degToRad(360),
      false,
    );
    ctx.fill();
  }

  requestAnimationFrame(draw);
}

draw();

Especificações

Specification
HTML Standard
# button-state-(type=button)

Compatibilidade com navegadores

BCD tables only load in the browser

Veja também