Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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----"+n.id)// 32,67,45
                           alert("job names----"+n.names)//test1,test2,test3

            html += '<option value="' + i + '">' + n.names + '</option>';
            i++;
        });
        $('#jobSel').html(html);
    });

i have to get the id of selected dropdown value..

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

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

<tr>
                        <td width="200px">Jobs</td>
                        <td> 
                            <select id="jobSel" class="longcombo"></select>
                        </td>
                    </tr> 
like image 286
Psl Avatar asked Nov 28 '22 04:11

Psl


1 Answers

Try this

on change event

$("#jodSel").on('change',function(){
    var getValue=$(this).val();
    alert(getValue);
  });

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>
    </select>
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>
    </select>

Jquery:

$("#example1").on('change', function () {
    alert($(this).val());
});

$("#example2").on('change', function () {
    alert($(this).find('option:selected').attr('id'));
});
like image 183
Satinder singh Avatar answered Dec 09 '22 18:12

Satinder singh