If Tom is selected from the drop down box, how do I get the name and not the value using jQuery so that the resulting output would be Tom?
<select id="emp" >
<option value=1>Tom</option>
<option value=12>Harold</option>e
<option value=32>Jenny</option>
</select>
- GeeksforGeeks How to select an element by name with jQuery ? In this article, we will learn to get the selected element by name in jQuery. An element can be selected by the name attribute using 2 methods: We will understand both methods with the help of examples. The name attribute selector can be used to select an element by its name.
The JQuery name attribute selector uses the Name attribute of the HTML tag to find a specific element. It is used to select all elements. It will select all p elements.
The jQuery .class attribute selector finds elements with a specific class. When a user clicks on a button, the element with class = “uniqueId” will be hidden. The JQuery name attribute selector uses the Name attribute of the HTML tag to find a specific element. It is used to select all elements.
Yes, we can set the option as selected using the val () method of jQuery. This is a jQuery built-in method. Basically, val () method can set the value attribute of any specified element, and also it can return the value of the element. Using this method, here we can have the option selected by specifying the value attribute beforehand.
var res = $('#emp :selected').text();
This gets the element with the ID emp
, then gets the descendant element that is :selected
, finally returns the .tex()
content.
Here's a plain javascript version:
var el = document.getElementById('emp');
var res = el.options[el.selectedIndex].text;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With