When using jQuery to set the value of input text fields, you can use the val() method. This method is intuitive and easy to use, as it can retrieve or set the values of form elements such as input fields, select boxes, and textareas.
Example Code:
Assume we have an HTML page with a text input field, and we want to automatically fill it when the page loads:
html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Set Input Value using jQuery</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <!-- Text input field --> <input type="text" id="myInput"> <script> $(document).ready(function() { // Execute after document is fully loaded $('#myInput').val("Hello, world!"); // Set input field value to "Hello, world!" }); </script> </body> </html>
Explanation:
- HTML Section: Contains an input field with the ID
myInput. - jQuery Section:
- First, we ensure the script runs after the document is fully loaded (
$(document).ready()). - Use the
$('#myInput')selector to find the element with IDmyInput. - Use the
.val("Hello, world!")method to set the value of the input field toHello, world!.
- First, we ensure the script runs after the document is fully loaded (
By using the above method, we can conveniently set the value of input fields dynamically as needed. This is very useful when handling user forms, displaying default values, or dynamically changing input content during user interaction.
2024年6月29日 12:07 回复