Método jQuery val()

❮ Métodos jQuery HTML/CSS

Exemplo

Defina o valor do campo <input>:

$("button").click(function(){
  $("input:text").val("Glenn Quagmire");
});

Definição e uso

O método val() retorna ou define o atributo value dos elementos selecionados.

Quando usado para retornar valor:
Este método retorna o valor do atributo value do PRIMEIRO elemento correspondido.

Quando usado para definir valor:
Este método define o valor do atributo value para TODOS os elementos correspondentes.

Nota: O método val() é usado principalmente com elementos de formulário HTML.


Sintaxe

Retorne o atributo value:

$(selector).val()

Defina o atributo de valor:

$(selector).val(value)

Defina o atributo value usando uma função:

$(selector).val(function(index,currentvalue))

Parameter Description
value Required. Specifies the value of the value attribute
function(index,currentvalue) Optional. Specifies a function that returns the value to set.
  • index - Returns the index position of the element in the set
  • currentvalue - Returns the current value attribute of selected elements

Experimente você mesmo - Exemplos


Como retornar o valor do atributo value do PRIMEIRO elemento correspondido.


Usando uma função para definir o valor do atributo value.


❮ Métodos jQuery HTML/CSS