How to set and get the value of form elements with jQuery?

To set and get the value of form elements with jQuery, you can use the .val() method.

To set the value of a form element:

  1. Select the element using a jQuery selector.
  2. Use the .val() method with the desired value as the argument.

Example:

// HTML: <input type="text" id="myInput"> // Set the value of the input element $('#myInput').val('Hello World');

To get the value of a form element:

  1. Select the element using a jQuery selector.
  2. Use the .val() method without any argument.

Example:

// HTML: <input type="text" id="myInput" value="Hello World"> // Get the value of the input element var inputValue = $('#myInput').val();

You can also set and get the values of multiple elements at once by using the same jQuery selector for all the elements.

Example:

// HTML: // <input type="text" id="input1" value="Value 1"> // <input type="text" id="input2" value="Value 2"> // Set the values of multiple input elements $('#input1, #input2').val('New Value'); // Get the values of multiple input elements var inputValues = $('#input1, #input2').val();

Note: The .val() method works for various types of form elements such as <input>, <select>, and <textarea>.