Print The Value of Selected Option in a Select List Form Using jQuery

jquery-print-form-selected-option

In this jQuery tutorial we will learn how to get and print the value of selected option of a select form.

Step 1: Create HTML Form with Select options

Let’s first create a HTML form with select options and a region to display the selected option.

1
2
3
4
5
6
7
8
9
<select>
  <option value="">-Select Location-</option>
  <option value="USA">USA</option>
  <option value="Canada">Canada</option>
  <option value="Japan">Japan</option>
  <option value="India">India</option>
</select>
<br /><br />
<div class="selection-message">You have selected: <span class="selected-option"></span></div>

Step 2: jQuery Code

Add below jQuery code on your page to print the selected option from a select list.
We can use val() method to get the value of the select options. We can also use text() method to get the text of the select options. In below example, I am using val() method to retrieve the value of the selected option.

1
2
3
4
5
6
7
8
9
<script>
$(document).ready(function(){
  $('select').change(function(){
    var selected_option = $(this).find(":selected").val();
    $('.selection-message').fadeIn();
    $('.selected-option').text(selected_option)
  })
})
</script>

Done!!
See below full code.

Full Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Get Value of Selected Option in a Select Form Using jQuery</title>
    <script src="//code.jquery.com/jquery-3.4.1.min.js"></script>
    <script>
    $(document).ready(function(){
      $('select').change(function(){
        var selected_option = $(this).find(":selected").val();
        $('.selection-message').fadeIn();
        $('.selected-option').text(selected_option)
      })
    })
    </script>
    <style>
    .selection-message {
      display: none;
      padding: 10px;
      background: yellow;
    }
    </style>
  </head>
  <body>
  <select>
    <option value="">-Select Location-</option>
    <option value="USA">USA</option>
    <option value="Canada">Canada</option>
    <option value="Japan">Japan</option>
    <option value="India">India</option>
  </select>
  <br /><br />
  <div class="selection-message">You have selected: <span class="selected-option"></span></div>
  </body>
</html>

Demo

Print The Value of Selected Option in a Select List Form

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *