Jquery to get the id of selected value from dropdown

前端 未结 4 1226
面向向阳花
面向向阳花 2021-02-10 14:26

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

$.get(\'/getJobs\', function (jobs) {
        seljobs = jobs;
        var i = 0;
        jobs.forE         


        
相关标签:
4条回答
  • 2021-02-10 15:08

    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'));
    });
    

    View Demo : For example 1 & 2

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

    My Blog : jQuery tutorials

    0 讨论(0)
  • 2021-02-10 15:09

    Try the change event and selected selector

    $('#jobSel').change(function(){
        var optId = $(this).find('option:selected').attr('id')
    })
    
    0 讨论(0)
  • 2021-02-10 15:23

    First set a custom attribute into your option for example nameid (you can set non-standardized attribute of an HTML element, it's allowed):

    '<option nameid= "' + n.id + "' value="' + i + '">' + n.names + '</option>'
    

    then you can easily get attribute value using jquery .attr() :

    $('option:selected').attr("nameid")
    

    For Example:

    <select id="jobSel" class="longcombo" onchange="GetNameId">
        <option nameid="32" value="1">test1</option>
        <option nameid="67" value="1">test2</option>
        <option nameid="45" value="1">test3</option>    
        </select>    
    

    Jquery:

    function GetNameId(){
       alert($('#jobSel option:selected').attr("nameid"));
    }
    
    0 讨论(0)
  • 2021-02-10 15:26

    If you are trying to get the id, then please update your code like

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

    To retrieve id,

    $('option:selected').attr("id")
    

    To retrieve Value

    $('option:selected').val()
    

    in Javascript

    var e = document.getElementById("jobSel");
    var job = e.options[e.selectedIndex].value;
    
    0 讨论(0)
提交回复
热议问题