What the difference between jQuery's functions val()
and text()
?
Where would you use one over the other?
attr('value') returns the value that was before editing input field. And . val() returns the current value.
The val() method returns or sets the value attribute of the selected elements. When used to return value: This method returns the value of the value attribute of the FIRST matched element.
Val (string) This built-in function returns the numeric value of a string of characters. The argument string is a sequence of characters that can be interpreted as a numeric value. The Val function stops reading the string at the first non-numeric character.
The difference between them is stated below: html() is used to return or change the html and text content of an element. text() can only return or change the text content of an element.
.val()
works on input elements (or any element with a value attribute?) and .text()
will not work on input elements. .val()
gets the value of the input element -- regardless of type. .text()
gets the innerText (not HTML) of all the matched elements:
.text()
The result is a string that contains the combined text contents of all matched elements. This method works on both HTML and XML documents. Cannot be used on input elements. For input field text use the val attribute.
.val()
Get the content of the value attribute of the first matched element
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With