jquery
  1. jquery-val

jQuery val()

The jQuery val() method is used to get or set the value of form fields like inputs, selects and textareas. It allows you to easily retrieve and manipulate the values of form elements on your webpage.

Syntax

// Get value of form element
$(selector).val();

// Set value of form element
$(selector).val(value);

Use

The val() method is often used in web development for working with form data like user input, search queries, and authentication. It can be used to quickly retrieve the value from a form element or to set the value programmatically.

Example

Here is an example of using jQuery val() method to get the value of a form input element:

<!DOCTYPE html>
<html>
  <head>
    <title>jQuery val() Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  </head>
  <body>
    <form>
      <label for="example-input">Example Input:</label>
      <input type="text" id="example-input" name="example-input">
    </form>
    <button id="get-value-button">Get Value</button>

    <script>
      $(document).ready(function () {
        $('#get-value-button').on('click', function () {
          const value = $('#example-input').val();
          alert(value);
        });
      });
    </script>
  </body>
</html>
Try Playground

In the example above, when the user clicks the "Get Value" button, the val() method is called on the #example-input selector to retrieve the input value and then alert logged.

Summary

jQuery val() is a versatile method that is used to work with form field elements in web development. It can be used to easily retrieve and manipulate values within the HTML DOM, making it a powerful tool for dealing with user input and other form data.

Published on: