Psl Psl - 5 months ago 29
Javascript Question

Jquery to get the id of selected value from dropdown

I have a drop down list that fetches values from db as follows

$.get('/getJobs', function (jobs) {
seljobs = jobs;
var i = 0;
jobs.forEach(function (n) {
alert("job id----" 32,67,45
alert("job names----"+n.names)//test1,test2,test3

html += '<option value="' + i + '">' + n.names + '</option>';

i have to get the
of selected dropdown value..

ic in my dropdown i have name values
ans assosiated
id's 32,67,45,

while selecting test1 i have to get id 32 and so ans so.How it is possible

<td width="200px">Jobs</td>
<select id="jobSel" class="longcombo"></select>


Try this

on change event

    var getValue=$(this).val();

Note: In dropdownlist if you want to set id,text relation from your database then, set id as value in option tag, not by adding extra id attribute inside option its not standard paractise though i did both in my answer but i prefer example 1

HTML Markup

Example 1:
    <select id="example1">
        <option value="1">one</option>
        <option value="2">two</option>
        <option value="3">three</option>
        <option value="4">four</option>
Example 2 :
    <select id="example2">
        <option id="1">one</option>
        <option id="2">two</option>
        <option id="3">three</option>
        <option id="4">four</option>


$("#example1").on('change', function () {

$("#example2").on('change', function () {

View Demo : For example 1, example 2

Blog Article : Get and Set dropdown list selected value with Jquery

Learn jQuery: Simple and easy jQuery tutorials blog