Home > Web Front-end > JS Tutorial > body text

Functions and examples of the val method in jQuery

WBOY
Release: 2024-02-28 14:39:03
Original
1053 people have browsed it

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.

  1. Get the value of the input input box

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);
Copy after login
  1. Set the value of the input input box

If we want to set a default value in the input box, we can Use the val() method:

$("#username").val("John Doe");
Copy after login
  1. Get the value of the select drop-down menu

If we have a drop-down menu