How to get the display value of Select using javascript

前端 未结 3 1214
闹比i
闹比i 2021-02-14 04:26

                        
    
提交评论

  • 2021-02-14 05:27

    In plain JavaScript you can do this:

    const show = () => {
      const sel = document.getElementById("Example"); // or this if only called onchange
      let value = sel.options[sel.selectedIndex].value; // or just sel.value
      let text = sel.options[sel.selectedIndex].text;
      console.log(value, text);
    }
    
    window.addEventListener("load", () => { // on load 
      document.getElementById("Example").addEventListener("change",show); // show on change
      show(); // show onload
    });
    <select id="Example">
      <option value="1">One</option>
      <option value="2">Two</option>
      <option value="3">Three</option>
    </select>

    jQuery:

    $(function() { // on load
      var $sel = $("#Example");
      $sel.on("change",function() {
        var value = $(this).val();
        var text = $("option:selected", this).text();
        console.log(value,text)
      }).trigger("change"); // initial call
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <select id="Example">
      <option value="1">One</option>
      <option value="2">Two</option>
      <option value="3">Three</option>
    </select>

    0 讨论(0)
  • 2021-02-14 05:27

    Here the selected text and value is getting using jquery when page load

    $(document).ready(function () {
    var ddlText = $("#ddlChar option:selected").text();
    var ddlValue = $("#ddlChar option:selected").val();
    });
    

    refer this

    http://csharpektroncmssql.blogspot.in/2012/03/jquery-how-to-select-dropdown-selected.html

    http://praveenbattula.blogspot.in/2009/08/jquery-how-to-set-value-in-drop-down-as.html

    0 讨论(0)
  • 提交回复
    热议问题