×

jQuery Tutorial

jQuery Examples

jQuery Practice

jQuery val() Method

jQuery | val() Method: Learn about the jQuery val() Method with its usages, syntax, and examples.
Submitted by Pratishtha Saxena, on September 26, 2022

val() Method

Value is an HTML attribute that is specified for an element and given a particular value. Generally, the value attribute is most used for the input tag in a form. The value attribute is also defined for other elements like – buttons, checkboxes, radio buttons, etc. The values for a button can be like – 'submit', 'button', 'reset', etc and this will define the text that will be visible on the button.

Now, val() is an inbuilt method of jQuery that helps to get the value of the selected form field or the element. The element is specified by using the selector and following it the val() method is executed. It then returns the value specified for that element. Since majorly the value attribute is used for a form input field or for a select tag, hence, the val() method is also used for those elements only.

val() Method Syntax

$(selector).val();

This is a very simple method and does not take any parameters for returning the value of the selected element in jQuery.

The below example shows the implementation of the val() method. When a particular option is selected from the drop-down created and the provided button is clicked afterward, then the val() method returns and displays the value of that specific option from the drop-down. Each option has different values specified.

jQuery val() Method Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
  </head>
  
  <body>
    <h2>jQuery - Val</h2>
    <p>Click the following button to get the value of the fields.</p>
    <button>Click Here</button>
    <hr>
    Week Days: 
    <select id="mySelect">
      <option value="Day One">Monday</option>
      <option value="Day Two">Tuesday</option>
      <option value="Day Three">Wednesday</option>
      <option value="Day Four">Thursday</option>
      <option value="Day Five">Friday</option>
      <option value="Day Six">Saturday</option>
      <option value="Day Seven">Sunday</option>
    </select>
    <h3></h3>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function() {
        $('button').click(function() {
            var value = $('#mySelect').val();
            $('h3').html(value);
        })
    });
  </script>
</html>

Output:

Example: jQuery val() Method


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.