Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

474
Visualizações
What's the difference between jQuery .val() and .attr('value')?

I think the title is clear enough

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

.val() works on all input type elements in a useful way, including <select>...even in the cases of <select multiple>, checkboxes, and radio buttons (in which .val() gets or sets an array of selected values not just a string).

So basically they serve different purposes, even though .attr('value') behaves the same in some situations, like textboxes. The preferred method is .val() to get consistent behavior everywhere.


Just for kicks, here's a lesser-known example for checkboxes that makes .val() handy:

<input name="mytest" type="checkbox" value="1">
<input name="mytest" type="checkbox" value="2">
<input name="mytest" type="checkbox" value="3">
<input name="mytest" type="checkbox" value="4">

You can do this:

$("input[name='mytest']").val([1, 2, 3]);

....which will check the first 3 boxes. You can give it a try here.

over 4 years ago · Santiago Trujillo Relatório

0

Also .attr('value') returns the value that was before editing input field. And .val() returns the current value.

over 4 years ago · Santiago Trujillo Relatório

0

To add to actis's answer...

Also .attr('value') returns the value that was before editing input field. And .val() returns the current value.

When working with a text entry field, the setter methods of .attr() and .val() work differently.

.val('newval')

will set the value the user sees on the page and update the value returned by subsequent .val() method calls. It will not set the value= attribute of the element.

OTOH

.attr('value','newval')

will set the value= attribute on the element. If the user hasn't typed and .val(newval) hasn't been called, then doing this will also visually update the control and update the value returned by .val().

You can investigate further with the following jsfiddle:

https://jsfiddle.net/jasonnet/vamLww2k/

Good luck.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda