In jquery, the val() method can be used to return the value of the value attribute of the first matching element, with the syntax "$(selector).val()"; it can also be used to set the value of all matching elements. The value of the attribute, the syntax is "$(selector).val("new value")".
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.
jquery val() method
In jquery, the val() method is used to return or set the value of the value attribute of the selected element. .
When used to return a value:
This method returns the value of the value attribute of the first matching element.
$(selector).val()
When used to set a value:
This method sets the value of the value attribute of all matching elements.
$(selector).val(value) //通过函数设置 value 属性: $(selector).val(function(index,currentvalue))
Example 1: Return the value of the value attribute of the first matching element.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-1.10.2.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ alert($("input").val()); }); }); </script> </head> <body> 喜欢的水果: <input type="text" name="fname" value="苹果"><br><br> <button>返回输入字段的值</button> </body> </html>
Example 2: Set the value of the field
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-1.10.2.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("input").val("榴莲"); }); }); </script> </head> <body> 喜欢的水果: <input type="text" name="fname" value="苹果"><br><br> <button>设置输入字段的值</button> </body> </html>
jQuery video tutorial、web front-end development video】
The above is the detailed content of How to use jquery val() method. For more information, please follow other related articles on the PHP Chinese website!