jQuery-get-specific-option-tag-text

Wikitechy | 555 Views | jquery | 03 Jun 2016

 


In jQuery get specific option tag is mainly used for selectors

  • :selected is used to define the “option” elements. 
  • :checked is used for checkboxes and radio inputs elements.

Syntax:

<select id='list'>
    <option value='1'>Option A</option>
    <option
value='2'>Option B</option>
    <option
value='3'>Option C</option>
</select>

Here is our syntax which defines to fetch the selected item from the drop down

Sample Code:

<!DOCTYPE html>
<html>
<head> 
    <title>
wikitechy - jQuery get specific option tag text</title> 
    <script
 src="http://code.jquery.com/jquery.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                var selectedval = $('#list').find(":selected").text();
                alert (selectedval);
            });         
        });
    </script>
</head>
<body> 
    <button>
Fetch Selected Option Text</button>
    <select
id='list'>
        <option
value='1'>Option A</option>
        <option
value='2'>Option B</option>
        <option
value='3'>Option C</option>
    </select>
</body> 
</html>

Code Explanation:

 

    Inside the <script src= ” http://code.jquery.com/jquery.js “> </script> the ajax library has been called using the (src)=source attribute.

    The $(document).ready(function);  - specifies that the document to be fully loaded and ready before working with it, in order to prevent any jQuery code from running before the document is finished loading.

    Here in this statement we are using the select element for creating a drop down and Using the option element we can give the option values for the drop down.

    $("button").click(function(){ - here is the button click event, which has been called here as element selector whose element “button” has been assigned for the click function.

    Here in this statement we fetch the value of the selected option by using the find:selected method and the value will be assigned for the variable “selectedval”.

Sample Output:



    On choosing option A form the “Fetch Selected Option Text “, the Alert for the value of the selected option pop ups the message saying “This page says: Option A “.

 

 

    On choosing option B form the “Fetch Selected Option Text “, the Alert for the value of the selected option pop ups the message saying “This page says: Option B “.



     On choosing option C form the “Fetch Selected Option Text “, the Alert for the value of the selected option pop ups the message saying “This page says: Option C “.




Workshop

IOT Hackathon
Webinar

Join our Community

Advertise