Home >Web Front-end >JS Tutorial >Understand the role of the val method in jQuery
The val() method in jQuery is a method used to get or set the value of a form element. Whether it is a text box, selection box, radio button or check box, the val() method can help us get the value in the input box, and can also be used to set the value of the input box. When writing code, it is very important to understand what the val() method does and how to use it.
First, let's look at a simple example to demonstrate the role of the val() method. Let's say we have a simple HTML form that contains a textbox and a button. We want to pop up the value in the text box and display it on the page after clicking the button. At this time, you can use the .val() method to get the value in the text box. The following is the sample code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>jQuery val()方法示例</title> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <input type="text" id="textInput"> <button id="showValue">显示数值</button> <div id="display"></div> <script> $(document).ready(function(){ $('#showValue').click(function(){ var textValue = $('#textInput').val(); $('#display').text(textValue); }); }); </script> </body> </html>
In the above example, we used the .val() method to get the value of the text box and display it on the page. When the button is clicked, the click event handler is triggered, which uses the .val() method to obtain the value in the text box and displays it on the page through the .text() method.
In addition to getting the value of the text box, the val() method can also be used to set the value of the text box. For example, if we want a text box to automatically populate when the page loads, we can use the .val() method to set an initial value. Here is another sample code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>jQuery val()方法示例</title> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <input type="text" id="textInput"> <button id="setValue">设置为Hello World</button> <script> $(document).ready(function(){ $('#setValue').click(function(){ $('#textInput').val("Hello World"); }); }); </script> </body> </html>
In this example, we use the .val() method to set the value of the text box to "Hello World". When the button is clicked, the click event handler function is triggered, in which the .val() method is used to set the value of the text box to "Hello World".
In summary, the val() method in jQuery is a very convenient method that can help us get and set the value of form elements. With appropriate code examples, we can better understand the usage and role of the val() method.
The above is the detailed content of Understand the role of the val method in jQuery. For more information, please follow other related articles on the PHP Chinese website!