jQuery attributes and styles (3)
There is a .val() method in jQuery that is mainly used to process the values of form elements, such as input, select and textarea.
val() method
val() has no parameters and gets the current value of the first element in the matched element set
val( value ), set the value of each element in the matched element set
val(function), a function used to return the set value
Note:
Pass .val( ) processes the select element. When no selection is selected, it returns null
The val() method is mostly used to set the value of the form field
Let’s take a look at a specific example and how to use it Val method
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script> </head> <body> <select id="see"> <option>php 中文网</option> <option>php.cn</option> <option>小猪 CMS</option> </select> <p></p> <script type="text/javascript"> $("p").text($('#see').val()); </script> </body> </html>
Let’s take a look at how to change the value of input
The code is as follows:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script> </head> <body> <input type="text" value="php 中文网" id="ipt"> <script type="text/javascript"> $("#ipt").val("php.cn"); </script> </body> </html>
Summary of the differences between html(), text() and val() :
.html(), .text(), and .val() are all used to read the content of the selected element; only .html() is used to read the html of the element. Content (including html tags), text() is used to read the plain text content of the element, including its descendant elements, and val() is used to read the "value" value of the form element. The html() and text() methods cannot be used on form elements, and val() can only be used on form elements; in addition, when the html() method is used on multiple elements, only the first element is read; val () method is the same as .html(). If it is applied to multiple elements, only the "value" value of the first form element can be read, but .text() is different from them. If .text() When applied to multiple elements, the text content of all selected elements will be read.
html(htmlString), text(textString) and val(value) are all used to replace the content of the selected element. If the three methods are used on multiple elements at the same time, they will be replaced. The contents of all selected elements.
html(), text(), and val() can all use the return value of the callback function to dynamically change the content of multiple elements.