Home >Web Front-end >JS Tutorial >Functions and examples of the val method in jQuery
Function and examples of the val method in jQuery
When programming with jQuery, it often involves getting or setting the value of a form element. At this time, you can use the val() method in jQuery. The val() method is a common method in jQuery, used to get or set the value of a form element. In this article, we will discuss the functionality of the val() method in detail and demonstrate its usage with concrete code examples.
1. Function of val() method
The val() method is used to get or set the value of form elements, which include input, textarea, select, etc. When the val() method takes no parameters, it returns the current value of the first element in the set of matching elements. When the val() method takes a parameter, it sets the value of all matching elements.
2. Sample code
The following is some sample code that shows how to use the val() method to get or set the value of a form element.
Suppose we have an input box, now we want Get the value entered by the user and output it to the console:
var username = $("#username").val(); console.log(username);
If we want to set a default value in the input box, we can Use the val() method:
$("#username").val("John Doe");
If we have a drop-down menu
<select id="city"> <option value="1">New York</option> <option value="2">Los Angeles</option> <option value="3">Chicago</option> </select>
We Want to get the value selected by the user:
var city = $("#city").val(); console.log(city);
If we want Los Angeles to be selected by default:
$("#city").val("2");
If we have a
<textarea id="message"></textarea>
We want to get the text entered by the user:
var message = $("#message").val(); console.log(message);
If we want to fill in the default text in the text box:
$("#message").val("Hello, world!");
Through the above sample code, we can see that the val() method is getting and setting Flexibility and practicality when it comes to the values of form elements. Through the demonstration combined with specific code examples, I hope readers can better understand the usage of the val() method and use it flexibly in their own projects.
The above is the detailed content of Functions and examples of the val method in jQuery. For more information, please follow other related articles on the PHP Chinese website!