How to get text of specific option tag using jQuery?
In order to select the text of a selected option or any specific option, jQuery allows doing that easily by its specific selectors. The selector is used to select the specific element.
Example: This example selects the text of the specific option(GFG_2) tag.
<!DOCTYPE html>
< html >
< head >
< title >
Get text of specific option tag
</ title >
< script src =
</ script >
</ head >
< body style = "text-align:center;" >
< h1 style = "color:green;" >
GeeksForGeeks
</ h1 >
< select id = 'GFG_list' >
< option value = 'GFG_1' >GFG_A</ option >
< option value = 'GFG_2' >GFG_B</ option >
< option value = 'GFG_3' >GFG_C</ option >
</ select >
< br >< br >
< button id = "GFG_Button" onclick = "getText()" >
getText
</ button >
< p id = "GFG_P" style = "color:green;font-size:20px;" ></ p >
< script >
function getText(){
var el = document.getElementById("GFG_P");
el.innerHTML = $("#GFG_list option[value='GFG_2']").text();
}
</ script >
</ body >
</ html >
|
Output:
-
Before clicking on the button:
-
After clicking on the button:
Example: This example selects the text of currently selected option tag.
<!DOCTYPE html>
< html >
< head >
< title >
Get text of specific option tag
</ title >
< script src =
</ script >
</ head >
< body style = "text-align:center;" >
< h1 style = "color:green;" >
GeeksForGeeks
</ h1 >
< select id = 'GFG_list' >
< option value = 'GFG_1' >GFG_A</ option >
< option value = 'GFG_2' >GFG_B</ option >
< option value = 'GFG_3' >GFG_C</ option >
</ select >
< br >< br >
< button id = "GFG_Button" onclick = "getText()" >
getText
</ button >
< p id = "GFG_P" style = "color:green; font-size: 20px;" ></ p >
< script >
function getText(){
var el = document.getElementById("GFG_P");
el.innerHTML = $("#GFG_list option:selected").text();
}
</ script >
</ body >
</ html >
|
Output:
-
Before clicking on the button:
-
After clicking on the button:
Last Updated :
22 Apr, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...